<html><head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
   <title>16.&nbsp;Web MVC framework</title><link rel="stylesheet" href="css/stylesheet.css" type="text/css"><meta name="generator" content="DocBook XSL Stylesheets V1.74.0"><link rel="home" href="index.html" title="Reference Documentation"><link rel="up" href="spring-web.html" title="Part&nbsp;V.&nbsp;The Web"><link rel="prev" href="spring-web.html" title="Part&nbsp;V.&nbsp;The Web"><link rel="next" href="view.html" title="17.&nbsp;View technologies"><!--Begin Google Analytics code--><script type="text/javascript">
			var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
			document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
		</script><script type="text/javascript">
			var pageTracker = _gat._getTracker("UA-2728886-3");
			pageTracker._setDomainName("none");
			pageTracker._setAllowLinker(true);
			pageTracker._trackPageview();
		</script><!--End Google Analytics code--></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">16.&nbsp;Web MVC framework</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="spring-web.html">Prev</a>&nbsp;</td><th width="60%" align="center">Part&nbsp;V.&nbsp;The Web</th><td width="20%" align="right">&nbsp;<a accesskey="n" href="view.html">Next</a></td></tr></table><hr></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="mvc"></a>16.&nbsp;Web MVC framework</h2></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="mvc-introduction"></a>16.1&nbsp;Introduction to Spring Web MVC framework</h2></div></div></div><p>The Spring Web model-view-controller (MVC) framework is designed
    around a <code class="classname">DispatcherServlet</code> that dispatches requests
    to handlers, with configurable handler mappings, view resolution, locale
    and theme resolution as well as support for uploading files. The default
    handler is based on the <code class="interfacename">@Controller</code> and
    <code class="interfacename">@RequestMapping</code> annotations, offering a
    wide range of flexible handling methods. With the introduction of Spring
    3.0, the <code class="interfacename">@Controller</code> mechanism also allows
    you to create RESTful Web sites and applications, through the
    <code class="interfacename">@PathVariable</code> annotation and other
    features.</p><div class="sidebar"><a name="mvc-open-for-extension"></a><p class="title"><b>&#8220;<span class="quote">Open for extension...</span>&#8221;</b></p><p>A key design principle in Spring Web MVC and in Spring in general
      is the &#8220;<span class="quote"><span class="emphasis"><em>Open for extension, closed for
      modification</em></span></span>&#8221; principle.</p><p>Some methods in the core classes of Spring Web MVC are marked
      <code class="literal">final</code>. As a developer you cannot override these
      methods to supply your own behavior. This has not been done arbitrarily,
      but specifically with this principal in mind.</p><p>For an explanation of this principle, refer to <span class="emphasis"><em>Expert
      Spring Web MVC and Web Flow</em></span> by Seth Ladd and others;
      specifically see the section "A Look At Design," on page 117 of the
      first edition. Alternatively, see</p><div class="orderedlist"><ol type="1"><li><p><a class="ulink" href="http://www.objectmentor.com/resources/articles/ocp.pdf" target="_top">Bob
          Martin, The Open-Closed Principle (PDF)</a></p></li></ol></div><p>You cannot add advice to final methods when you use Spring MVC.
      For example, you cannot add advice to the
      <code class="literal">AbstractController.setSynchronizeOnSession()</code> method. Refer to
      <a class="xref" href="aop.html#aop-understanding-aop-proxies" title="8.6.1&nbsp;Understanding AOP proxies">Section&nbsp;8.6.1, &#8220;Understanding AOP proxies&#8221;</a> for more information on
      AOP proxies and why you cannot add advice to final methods.</p></div><p>In Spring Web MVC you can use any object as a command or
    form-backing object; you do not need to implement a framework-specific
    interface or base class. Spring's data binding is highly flexible: for
    example, it treats type mismatches as validation errors that can be
    evaluated by the application, not as system errors. Thus you need not
    duplicate your business objects' properties as simple, untyped strings in
    your form objects simply to handle invalid submissions, or to convert the
    Strings properly. Instead, it is often preferable to bind directly to your
    business objects.</p><p>Spring's view resolution is extremely flexible. A
    <code class="interfacename">Controller</code> is typically responsible for preparing
    a model <code class="classname">Map</code> with data and selecting a view name but it 
    can also write directly to the response stream and complete the request. 
    View name resolution is highly configurable through file extension or Accept header 
    content type negotiation, through bean names, a properties file,
    or even a custom <code class="interfacename">ViewResolver</code>
    implementation. The model (the M in MVC) is a
    <code class="interfacename">Map</code> interface, which allows for the
    complete abstraction of the view technology. You can integrate directly with 
    template based rendering technologies such as JSP, Velocity and Freemarker, 
    or directly generate XML, JSON, Atom, and many other types of content. 
    The model <code class="interfacename">Map</code> is simply transformed into an
    appropriate format, such as JSP request attributes, a Velocity template
    model.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-features"></a>16.1.1&nbsp;Features of Spring Web MVC</h3></div></div></div><div class="sidebar"><p class="title"><b>Spring Web Flow</b></p><p>Spring Web Flow (SWF) aims to be the best solution for the management
  of web application page flow.</p><p>SWF integrates with existing frameworks like Spring MVC, Struts, and
  JSF, in both servlet and portlet environments. If you have a business
  process (or processes) that would benefit from a conversational model as
  opposed to a purely request model, then SWF may be the solution.</p><p>SWF allows you to capture logical page flows as self-contained modules
  that are reusable in different situations, and as such is ideal for building
  web application modules that guide the user through controlled navigations
  that drive business processes.</p><p>For more information about SWF, consult the
  <a class="ulink" href="http://www.springframework.org/webflow" target="_top">Spring Web Flow website</a>.
  </p></div><p>Spring's web module includes many unique web support
      features:</p><div class="itemizedlist"><ul type="disc"><li><p><span class="emphasis"><em>Clear separation of roles</em></span>. Each role --
          controller, validator, command object, form object, model object,
          <code class="classname">DispatcherServlet</code>, handler mapping, view
          resolver, and so on -- can be fulfilled by a specialized
          object.</p></li><li><p><span class="emphasis"><em>Powerful and straightforward configuration of both
          framework and application classes as JavaBeans</em></span>. This
          configuration capability includes easy referencing across contexts,
          such as from web controllers to business objects and
          validators.</p></li><li><p><span class="emphasis"><em>Adaptability, non-intrusiveness, and
          flexibility.</em></span> Define any controller method signature you
          need, possibly using one of the parameter annotations (such as
          @RequestParam, @RequestHeader, @PathVariable, and more) for a given
          scenario.</p></li><li><p><span class="emphasis"><em>Reusable business code</em></span>,<span class="emphasis"><em> no need
          for duplication</em></span>. Use existing business objects as command
          or form objects instead of mirroring them to extend a particular
          framework base class.</p></li><li><p><span class="emphasis"><em>Customizable binding and validation</em></span>. Type
          mismatches as application-level validation errors that keep the
          offending value, localized date and number binding, and so on
          instead of String-only form objects with manual parsing and
          conversion to business objects.</p></li><li><p><span class="emphasis"><em>Customizable handler mapping and view
          resolution</em></span>. Handler mapping and view resolution
          strategies range from simple URL-based configuration, to
          sophisticated, purpose-built resolution strategies. Spring is more
          flexible than web MVC frameworks that mandate a particular
          technique.</p></li><li><p><span class="emphasis"><em>Flexible model transfer</em></span>. Model transfer
          with a name/value <code class="interfacename">Map</code> supports easy
          integration with any view technology.</p></li><li><p><span class="emphasis"><em>Customizable locale and theme resolution, support
          for JSPs with or without Spring tag library, support for JSTL,
          support for Velocity without the need for extra bridges, and so
          on.</em></span></p></li><li><p><span class="emphasis"><em>A simple yet powerful JSP tag library known as the
          Spring tag library that provides support for features such as data
          binding and themes</em></span>. The custom tags allow for maximum
          flexibility in terms of markup code. For information on the tag
          library descriptor, see the appendix entitled <a class="xref" href="spring.tld.html" title="Appendix&nbsp;F.&nbsp;spring.tld">Appendix&nbsp;F, <i>spring.tld</i></a></p></li><li><p><span class="emphasis"><em>A JSP form tag library, introduced in Spring 2.0,
          that makes writing forms in JSP pages much easier.</em></span> For
          information on the tag library descriptor, see the appendix entitled
          <a class="xref" href="spring-form.tld.html" title="Appendix&nbsp;G.&nbsp;spring-form.tld">Appendix&nbsp;G, <i>spring-form.tld</i></a></p></li><li><p><span class="emphasis"><em>Beans whose lifecycle is scoped to the current HTTP
          request or HTTP <code class="interfacename">Session</code>.</em></span>
          This is not a specific feature of Spring MVC itself, but rather of
          the <code class="interfacename">WebApplicationContext</code>
          container(s) that Spring MVC uses. These bean scopes are described
          in <a class="xref" href="beans.html#beans-factory-scopes-other" title="4.5.4&nbsp;Request, session, and global session scopes">Section&nbsp;4.5.4, &#8220;Request, session, and global session scopes&#8221;</a></p></li></ul></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-introduction-pluggability"></a>16.1.2&nbsp;Pluggability of other MVC implementations</h3></div></div></div><p>Non-Spring MVC implementations are preferable for some projects.
      Many teams expect to leverage their existing investment in skills and
      tools. A large body of knowledge and experience exist for the Struts
      framework. If you can abide Struts' architectural flaws, it can be a
      viable choice for the web layer; the same applies to WebWork and other
      web MVC frameworks.</p><p>If you do not want to use Spring's web MVC, but intend to leverage
      other solutions that Spring offers, you can integrate the web MVC
      framework of your choice with Spring easily. Simply start up a Spring
      root application context through its
      <code class="classname">ContextLoaderListener</code>, and access it through
      its
      <code class="interfacename">ServletContext</code> attribute (or Spring's
      respective helper method) from within a Struts or WebWork action. No
      "plug-ins" are involved, so no dedicated integration is necessary. From
      the web layer's point of view, you simply use Spring as a library, with
      the root application context instance as the entry point.</p><p>Your registered beans and Spring's services can be at your
      fingertips even without Spring's Web MVC. Spring does not compete with
      Struts or WebWork in this scenario. It simply addresses the many areas
      that the pure web MVC frameworks do not, from bean configuration to data
      access and transaction handling. So you can enrich your application with
      a Spring middle tier and/or data access tier, even if you just want to
      use, for example, the transaction abstraction with JDBC or
      Hibernate.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="mvc-servlet"></a>16.2&nbsp;The <code class="classname">DispatcherServlet</code></h2></div></div></div><p>Spring's web MVC framework is, like many other web MVC frameworks,
    request-driven, designed around a central servlet that dispatches requests
    to controllers and offers other functionality that facilitates the
    development of web applications. Spring's
    <code class="classname">DispatcherServlet</code> however, does more than just
    that. It is completely integrated with the Spring IoC container and as
    such allows you to use every other feature that Spring has.</p><p>The request processing workflow of the Spring Web MVC
    <code class="classname">DispatcherServlet</code> is illustrated in the following
    diagram. The pattern-savvy reader will recognize that the
    <code class="classname">DispatcherServlet</code> is an expression of the
    &#8220;<span class="quote">Front Controller</span>&#8221; design pattern (this is a pattern that
    Spring Web MVC shares with many other leading web frameworks).</p><div class="mediaobject" align="center"><img src="images/mvc.png" align="middle"><div class="caption"><p>The request processing workflow in Spring Web MVC
        (high level)</p></div></div><p>The <code class="classname">DispatcherServlet</code> is an actual
    <code class="interfacename">Servlet</code> (it inherits from the
    <code class="classname">HttpServlet</code> base class), and as such is declared in
    the <code class="literal">web.xml</code> of your web application. You need to map
    requests that you want the <code class="classname">DispatcherServlet</code> to
    handle, by using a URL mapping in the same <code class="literal">web.xml</code>
    file. This is standard J2EE servlet configuration; the following example
    shows such a <code class="classname">DispatcherServlet</code> declaration and
    mapping:</p><pre class="programlisting">&lt;<span class="hl-tag">web-app</span>&gt;

    &lt;<span class="hl-tag">servlet</span>&gt;
        &lt;<span class="hl-tag">servlet-name</span>&gt;example&lt;<span class="hl-tag">/servlet-name</span>&gt;
        &lt;<span class="hl-tag">servlet-class</span>&gt;org.springframework.web.servlet.DispatcherServlet&lt;<span class="hl-tag">/servlet-class</span>&gt;
        &lt;<span class="hl-tag">load-on-startup</span>&gt;1&lt;<span class="hl-tag">/load-on-startup</span>&gt;
    &lt;<span class="hl-tag">/servlet</span>&gt;

    &lt;<span class="hl-tag">servlet-mapping</span>&gt;
        &lt;<span class="hl-tag">servlet-name</span>&gt;example&lt;<span class="hl-tag">/servlet-name</span>&gt;
        &lt;<span class="hl-tag">url-pattern</span>&gt;/example/*&lt;<span class="hl-tag">/url-pattern</span>&gt;
    &lt;<span class="hl-tag">/servlet-mapping</span>&gt;

&lt;<span class="hl-tag">/web-app</span>&gt;</pre><p>In the preceding example, all requests startig with
    <code class="literal">/example</code> will be handled by the <code class="classname">DispatcherServlet</code>
    instance named <code class="literal">example</code>. This is only the first step in
    setting up Spring Web MVC. You
    now need to configure the various beans used by the Spring Web MVC
    framework (over and above the <code class="classname">DispatcherServlet</code>
    itself).</p><p>As detailed in <a class="xref" href="beans.html#context-introduction" title="4.14&nbsp;Additional Capabilities of the ApplicationContext">Section&nbsp;4.14, &#8220;Additional Capabilities of the
    ApplicationContext&#8221;</a>,
    <code class="interfacename">ApplicationContext</code> instances in Spring can
    be scoped. In the Web MVC framework, each
    <code class="classname">DispatcherServlet</code> has its own
    <code class="interfacename">WebApplicationContext</code>, which inherits all
    the beans already defined in the root
    <code class="interfacename">WebApplicationContext</code>. These inherited
    beans can be overridden in the servlet-specific scope, and you can define
    new scope-specific beans local to a given servlet instance.</p><div class="mediaobject" align="center"><img src="images/mvc-contexts.gif" align="middle"><div class="caption">Context hierarchy in Spring Web MVC</div></div><p>Upon initialization of a <code class="classname">DispatcherServlet</code>,
    the framework <span class="emphasis"><em><span class="emphasis"><em>looks
    for a file named</em></span>
    <code class="literal">[servlet-name]-servlet.xml</code></em></span> in the
    <code class="literal">WEB-INF</code> directory of your web application and creates
    the beans defined there, overriding the definitions of any beans defined
    with the same name in the global scope.</p><p>Consider the following <code class="classname">DispatcherServlet</code>
    servlet configuration (in the <code class="literal">web.xml</code> file):</p><pre class="programlisting">&lt;<span class="hl-tag">web-app</span>&gt;

    &lt;<span class="hl-tag">servlet</span>&gt;
        &lt;<span class="hl-tag">servlet-name</span>&gt;golfing&lt;<span class="hl-tag">/servlet-name</span>&gt;
        &lt;<span class="hl-tag">servlet-class</span>&gt;org.springframework.web.servlet.DispatcherServlet&lt;<span class="hl-tag">/servlet-class</span>&gt;
        &lt;<span class="hl-tag">load-on-startup</span>&gt;1&lt;<span class="hl-tag">/load-on-startup</span>&gt;
    &lt;<span class="hl-tag">/servlet</span>&gt;

    &lt;<span class="hl-tag">servlet-mapping</span>&gt;
        &lt;<span class="hl-tag">servlet-name</span>&gt;golfing&lt;<span class="hl-tag">/servlet-name</span>&gt;
        &lt;<span class="hl-tag">url-pattern</span>&gt;/golfing/*&lt;<span class="hl-tag">/url-pattern</span>&gt;
    &lt;<span class="hl-tag">/servlet-mapping</span>&gt;

&lt;<span class="hl-tag">/web-app</span>&gt;</pre><p>With the above servlet configuration in place, you
    will need to have a file called <code class="literal">/WEB-INF/</code><span class="bold"><strong>golfing</strong></span><code class="literal">-servlet.xml</code> in your
    application; this file will contain all of your Spring Web MVC-specific
    components (beans). You can change the exact location of this
    configuration file through a servlet initialization parameter (see below
    for details).</p><p>The <code class="interfacename">WebApplicationContext</code> is an
    extension of the plain <code class="interfacename">ApplicationContext</code>
    that has some extra features necessary for web applications. It differs
    from a normal <code class="interfacename">ApplicationContext</code> in that it
    is capable of resolving themes (see <a class="xref" href="mvc.html#mvc-themeresolver" title="16.7&nbsp;Using themes">Section&nbsp;16.7, &#8220;Using themes&#8221;</a>),
    and that it knows which servlet it is associated with (by having a link to
    the <code class="interfacename">ServletContext</code>). The
    <code class="interfacename">WebApplicationContext</code> is bound in the
    <code class="interfacename">ServletContext</code>, and by using static methods
    on the <code class="classname">RequestContextUtils</code> class you can always
    look up the <code class="interfacename">WebApplicationContext</code> if you
    need access to it.</p><p>The Spring <code class="classname">DispatcherServlet</code> uses special
    beans to process requests and render the appropriate views. These beans
    are part of Spring Framework. You can configure them in the
    <code class="interfacename">WebApplicationContext</code>, just as you
    configure any other bean. However, for most beans, sensible defaults are
    provided so you initially do not need to configure them. These
    beans are described in the following table.</p><div class="table"><a name="mvc-webappctx-special-beans-tbl"></a><p class="title"><b>Table&nbsp;16.1.&nbsp;Special beans in the
      <code class="interfacename">WebApplicationContext</code></b></p><div class="table-contents"><table summary="Special beans in the&#xA;      WebApplicationContext" style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Bean type</th><th style="border-bottom: 1.0pt solid ; ">Explanation</th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><a class="link" href="mvc.html#mvc-controller" title="16.3&nbsp;Implementing Controllers">controllers</a></td><td style="border-bottom: 1.0pt solid ; ">Form the <code class="literal">C</code> part of the MVC.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><a class="link" href="mvc.html#mvc-handlermapping" title="16.4&nbsp;Handler mappings">handler
            mappings</a></td><td style="border-bottom: 1.0pt solid ; ">Handle the execution of a list of pre-processors and
            post-processors and controllers that will be executed if they
            match certain criteria (for example, a matching URL specified with
            the controller).</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><a class="link" href="mvc.html#mvc-viewresolver" title="16.5&nbsp;Resolving views">view
            resolvers</a></td><td style="border-bottom: 1.0pt solid ; ">Resolves view names to views.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><a class="link" href="mvc.html#mvc-localeresolver" title="16.6&nbsp;Using locales">locale
            resolver</a></td><td style="border-bottom: 1.0pt solid ; ">A <a class="link" href="mvc.html#mvc-localeresolver" title="16.6&nbsp;Using locales">locale resolver</a>
            is a component capable of resolving the locale a client is using,
            in order to be able to offer internationalized views</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Theme resolver</td><td style="border-bottom: 1.0pt solid ; ">A <a class="link" href="mvc.html#mvc-themeresolver" title="16.7&nbsp;Using themes">theme resolver</a>
            is capable of resolving themes your web application can use, for
            example, to offer personalized layouts</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">multipart file resolver</td><td style="border-bottom: 1.0pt solid ; ">Contains functionality to process file uploads from HTML
            forms.</td></tr><tr><td style="border-right: 1.0pt solid ; "><a class="link" href="mvc.html#mvc-exceptionhandlers" title="16.9&nbsp;Handling exceptions">handler exception
            resolvers</a></td><td style="">Contains functionality to map exceptions to views or
            implement other more complex exception handling code.</td></tr></tbody></table></div></div><br class="table-break"><p>After you set up a <code class="classname">DispatcherServlet</code>, and a
    request comes in for that specific
    <code class="classname">DispatcherServlet</code>, the
    <code class="classname">DispatcherServlet</code> starts processing the request as
    follows:</p><div class="orderedlist"><ol type="1"><li><p>The <code class="interfacename">WebApplicationContext</code> is
        searched for and bound in the request as an attribute that the
        controller and other elements in the process can use. It
        is bound by default under the key
        <code class="literal">DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE</code>.</p></li><li><p>The locale resolver is bound to the request to enable elements
        in the process to resolve the locale to use when processing the
        request (rendering the view, preparing data, and so on). If you do not
        need locale resolving, you do not need it.</p></li><li><p>The theme resolver is bound to the request to let elements such
        as views determine which theme to use. If you do not use themes, you
        can ignore it.</p></li><li><p>If you specify a multipart file resolver, the request is
        inspected for multiparts; if multiparts are found, the request is
        wrapped in a <code class="classname">MultipartHttpServletRequest</code> for
        further processing by other elements in the process. (See <a class="xref" href="mvc.html#mvc-multipart-resolver" title="16.8.2&nbsp;Using the MultipartResolver">Section&nbsp;16.8.2, &#8220;Using the
      MultipartResolver&#8221;</a> for further information about
        multipart handling).</p></li><li><p>An appropriate handler is searched for. If a handler is found,
        the execution chain associated with the handler (preprocessors,
        postprocessors, and controllers) is executed in order to prepare a
        model or rendering.</p></li><li><p>If a model is returned, the view is rendered. If no model is
        returned, (may be due to a preprocessor or postprocessor intercepting
        the request, perhaps for security reasons), no view is rendered,
        because the request could already have been fulfilled.</p></li></ol></div><p>Handler exception resolvers that are declared in the
    <code class="interfacename">WebApplicationContext</code> pick up exceptions
    that are thrown during processing of the request. Using these exception
    resolvers allows you to define custom behaviors to address
    exceptions.</p><p>The Spring <code class="classname">DispatcherServlet</code> also supports
    the return of the <span class="emphasis"><em>last-modification-date</em></span>, as
    specified by the Servlet API. The process of determining the last
    modification date for a specific request is straightforward: the
    <code class="classname">DispatcherServlet</code> looks up an appropriate handler
    mapping and tests whether the handler that is found implements the
    <span class="emphasis"><em><code class="interfacename">LastModified</code></em></span>
    interface. If so, the value of the <code class="literal">long
    getLastModified(request)</code> method of the
    <code class="interfacename">LastModified</code> interface is returned to the
    client.</p><p>You can customize individual
    <code class="classname">DispatcherServlet</code> instances by adding servlet
    initialization parameters (<code class="literal">init-param</code> elements) to the
    servlet declaration in the <code class="literal">web.xml</code> file. See the
    following table for the list of supported parameters.</p><div class="table"><a name="mvc-disp-servlet-init-params-tbl"></a><p class="title"><b>Table&nbsp;16.2.&nbsp;<code class="classname">DispatcherServlet</code> initialization
      parameters</b></p><div class="table-contents"><table summary="DispatcherServlet initialization&#xA;      parameters" style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Parameter</th><th style="border-bottom: 1.0pt solid ; ">Explanation</th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="literal">contextClass</code></td><td style="border-bottom: 1.0pt solid ; ">Class that implements
            <code class="interfacename">WebApplicationContext</code>, which
            instantiates the context used by this servlet. By default, the
            <code class="classname">XmlWebApplicationContext</code> is used.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="literal">contextConfigLocation</code></td><td style="border-bottom: 1.0pt solid ; ">String that is passed to the context instance (specified by
            <code class="literal">contextClass</code>) to indicate where context(s) can
            be found. The string consists potentially of multiple strings
            (using a comma as a delimiter) to support multiple contexts. In
            case of multiple context locations with beans that are defined
            twice, the latest location takes precedence.</td></tr><tr><td style="border-right: 1.0pt solid ; "><code class="literal">namespace</code></td><td style="">Namespace of the
            <code class="interfacename">WebApplicationContext</code>. Defaults to
            <code class="literal">[servlet-name]-servlet</code>.</td></tr></tbody></table></div></div><br class="table-break"></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="mvc-controller"></a>16.3&nbsp;Implementing Controllers</h2></div></div></div><p>Controllers provide access to the application behavior that you
    typically define through a service interface. Controllers
    interpret user input and transform it into a model that is represented to
    the user by the view. Spring implements a controller in a very abstract
    way, which enables you to create a wide variety of controllers.</p><p>Spring 2.5 introduced an annotation-based programming model for MVC
    controllers that uses annotations such as
    <code class="interfacename">@RequestMapping</code>,
    <code class="interfacename">@RequestParam</code>,
    <code class="interfacename">@ModelAttribute</code>, and so on. This annotation
    support is available for both Servlet MVC and Portlet MVC. Controllers
    implemented in this style do not have to extend specific base classes or
    implement specific interfaces. Furthermore, they do not usually have
    direct dependencies on Servlet or Portlet APIs, although you can easily
    configure access to Servlet or Portlet facilities.</p><div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Tip"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Tip]" src="images/tip.gif"></td><th align="left">Tip</th></tr><tr><td align="left" valign="top"><p>Available in the <a class="link" href="new-in-3.0.html#new-in-3.0-samples">samples repository</a>,
      a number of web applications leverage the annotation support described in this section 
      including <span class="emphasis"><em>MvcShowcase</em></span>, <span class="emphasis"><em>MvcAjax</em></span>,
      <span class="emphasis"><em>MvcBasic</em></span>, <span class="emphasis"><em>PetClinic</em></span>, 
      <span class="emphasis"><em>PetCare</em></span>, and others.</p></td></tr></table></div><pre class="programlisting">@Controller
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> HelloWorldController {

    @RequestMapping(<span class="hl-string">"/helloWorld"</span>)
    <span class="hl-keyword">public</span> String helloWorld(Model model) {
        model.addAttribute(<span class="hl-string">"message"</span>, <span class="hl-string">"Hello World!"</span>);
        <span class="hl-keyword">return</span> <span class="hl-string">"helloWorld"</span>;
    }
}</pre><p>As you can see, the <code class="interfacename">@Controller</code> and
    <code class="interfacename">@RequestMapping</code> annotations allow flexible
    method names and signatures. In this particular example the method accepts
    a <code class="classname">Model</code> and returns a view name as a 
    <code class="classname">String</code>, but various other method parameters and 
    return values can be used as explained later in this section. 
    <code class="interfacename">@Controller</code> and 
    <code class="interfacename">@RequestMapping</code> and a number of other 
    annotations form the basis for the Spring MVC implementation. 
    This section documents these annotations and
    how they are most commonly used in a Servlet environment.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-ann-controller"></a>16.3.1&nbsp;Defining a controller with
      <code class="interfacename">@Controller</code></h3></div></div></div><p>The <code class="interfacename">@Controller</code> annotation
      indicates that a particular class serves the role of a
      <span class="emphasis"><em>controller</em></span>. Spring does not require you to extend
      any controller base class or reference the Servlet API. However, you can
      still reference Servlet-specific features if you need to.</p><p>The <code class="interfacename">@Controller</code> annotation acts as
      a stereotype for the annotated class, indicating its role. The
      dispatcher scans such annotated classes for mapped methods and detects
      <code class="interfacename">@RequestMapping</code> annotations (see the next
      section).</p><p>You can define annotated controller beans explicitly, using a
      standard Spring bean definition in the dispatcher's context. However,
      the <code class="interfacename">@Controller</code> stereotype also allows
      for autodetection, aligned with Spring general support for detecting
      component classes in the classpath and auto-registering bean definitions
      for them.</p><p>To enable autodetection of such annotated controllers, you add
      component scanning to your configuration. Use the
      <span class="emphasis"><em>spring-context</em></span> schema as shown in the following XML
      snippet:</p><pre class="programlisting">&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span> 
    <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
    <span class="hl-attribute">xmlns:p</span>=<span class="hl-value">"http://www.springframework.org/schema/p"</span> 
    <span class="hl-attribute">xmlns:context</span>=<span class="hl-value">"http://www.springframework.org/schema/context"</span>
    <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd"</span>&gt;

    &lt;<span class="hl-tag">context:component-scan</span> <span class="hl-attribute">base-package</span>=<span class="hl-value">"org.springframework.samples.petclinic.web"</span>/&gt;

    // ...

&lt;<span class="hl-tag">/beans</span>&gt;</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-ann-requestmapping"></a>16.3.2&nbsp;Mapping Requests With
      <code class="interfacename">@RequestMapping</code></h3></div></div></div><p>You use the <code class="interfacename">@RequestMapping</code>
      annotation to map URLs such as <code class="filename">/appointments</code> onto
      an entire class or a particular handler method. Typically the
      class-level annotation maps a specific request path (or path pattern)
      onto a form controller, with additional method-level annotations
      narrowing the primary mapping for a specific HTTP method request method
      ("GET", "POST", etc.) or an HTTP request parameter condition.</p><p>The following example from the <span class="emphasis"><em>Petcare</em></span> sample shows 
      a controller in a Spring MVC application that uses this annotation:</p><pre class="programlisting">@Controller
@RequestMapping(<span class="hl-string">"/appointments"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> AppointmentsController {

    <span class="hl-keyword">private</span> <span class="hl-keyword">final</span> AppointmentBook appointmentBook;
    
    @Autowired
    <span class="hl-keyword">public</span> AppointmentsController(AppointmentBook appointmentBook) {
        <span class="hl-keyword">this</span>.appointmentBook = appointmentBook;
    }

    @RequestMapping(method = RequestMethod.GET)
    <span class="hl-keyword">public</span> Map&lt;String, Appointment&gt; get() {
        <span class="hl-keyword">return</span> appointmentBook.getAppointmentsForToday();
    }

    @RequestMapping(value=<span class="hl-string">"/{day}"</span>, method = RequestMethod.GET)
    <span class="hl-keyword">public</span> Map&lt;String, Appointment&gt; getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
        <span class="hl-keyword">return</span> appointmentBook.getAppointmentsForDay(day);
    }

    @RequestMapping(value=<span class="hl-string">"/new"</span>, method = RequestMethod.GET)
    <span class="hl-keyword">public</span> AppointmentForm getNewForm() {
        <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> AppointmentForm();
    }

    @RequestMapping(method = RequestMethod.POST)
    <span class="hl-keyword">public</span> String add(@Valid AppointmentForm appointment, BindingResult result) {
        <span class="hl-keyword">if</span> (result.hasErrors()) {
            <span class="hl-keyword">return</span> <span class="hl-string">"appointments/new"</span>;
        }
        appointmentBook.addAppointment(appointment);
        <span class="hl-keyword">return</span> <span class="hl-string">"redirect:/appointments"</span>;
    }
}</pre><p>In the example, the <code class="interfacename">@RequestMapping</code>
      is used in a number of places. The first usage is on the type (class)
      level, which indicates that all handling methods on this controller are
      relative to the <code class="filename">/appointments</code> path. The
      <code class="methodname">get()</code> method has a further
      <code class="interfacename">@RequestMapping</code> refinement: it only
      accepts GET requests, meaning that an HTTP GET for
      <code class="filename">/appointments</code> invokes this method. The
      <code class="methodname">post()</code> has a similar refinement, and the
      <code class="methodname">getNewForm()</code> combines the definition of HTTP
      method and path into one, so that GET requests for
      <code class="filename">appointments/new</code> are handled by that method.</p><p>The <code class="methodname">getForDay()</code> method shows another
      usage of <code class="interfacename">@RequestMapping</code>: URI templates.
      (See <a class="link" href="mvc.html#mvc-ann-requestmapping-uri-templates" title="16.3.2.1&nbsp;URI Template Patterns">the next
      section </a>).</p><p>A <code class="interfacename">@RequestMapping</code> on the class
      level is not required. Without it, all paths are simply absolute, and
      not relative. The following example from the <span class="emphasis"><em>PetClinic</em></span> sample
      application shows a multi-action controller using
      <code class="classname">@RequestMapping</code>:</p><pre class="programlisting">@Controller
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ClinicController {

    <span class="hl-keyword">private</span> <span class="hl-keyword">final</span> Clinic clinic;

    @Autowired
    <span class="hl-keyword">public</span> ClinicController(Clinic clinic) {
        <span class="hl-keyword">this</span>.clinic = clinic;
    }

    @RequestMapping(<span class="hl-string">"/"</span>)
    <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> welcomeHandler() {
    }

    @RequestMapping(<span class="hl-string">"/vets"</span>)
    <span class="hl-keyword">public</span> ModelMap vetsHandler() {
        <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> ModelMap(<span class="hl-keyword">this</span>.clinic.getVets());
    }

}</pre><div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Tip: Using @RequestMapping On Interface Methods"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Tip]" src="images/tip.gif"></td><th align="left">Using @RequestMapping On Interface Methods</th></tr><tr><td align="left" valign="top"><p>
		  A common pitfall when working with annotated controller classes
		  happens when applying functionality that requires creating a proxy
		  for the controller object (e.g.
		  <code class="interfacename">@Transactional</code> methods). Usually you
		  will introduce an interface for the controller in order to use JDK
		  dynamic proxies. To make this work you must move the
		  <code class="interfacename">@RequestMapping</code> annotations to the
		  interface as well as the mapping mechanism can only "see" the interface
		  exposed by the proxy. Alternatively, you could activate
		  <code class="code">proxy-target-class="true"</code> in the configuration for the
		  functionality applied to the controller (in our transaction scenario
		  in <code class="code">&lt;tx:annotation-driven /&gt;</code>). Doing so indicates
		  that CGLIB-based subclass proxies should be used instead of
		  interface-based JDK proxies. For more information on various proxying
		  mechanisms see <a class="xref" href="aop.html#aop-proxying" title="8.6&nbsp;Proxying mechanisms">Section&nbsp;8.6, &#8220;Proxying mechanisms&#8221;</a>.
		</p></td></tr></table></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-requestmapping-uri-templates"></a>16.3.2.1&nbsp;URI Template Patterns</h4></div></div></div><p><span class="emphasis"><em>URI templates</em></span> can be used for convenient access to selected
        segments of a URL in a <code class="interfacename">@RequestMapping</code> method.</p><p>A URI Template is a URI-like string, containing one or more
		variable names. When you substitute values for these variables, the
		template becomes a URI. The <a class="ulink" href="http://bitworking.org/projects/URI-Templates/" target="_top">proposed RFC</a> for URI Templates
		defines how a URI is parameterized. For example, the URI Template 
		<code class="code">http://www.example.com/users/{userId}</code> contains the variable 
		<span class="emphasis"><em>userId</em></span>. Assigning the value <span class="emphasis"><em>fred</em></span> to the variable 
		yields <code class="code">http://www.example.com/users/fred</code>.</p><p>In Spring MVC you can apply the <code class="interfacename">@PathVariable</code> annotation
        to a method argument to indicate that it is bound to the value of a URI template variable:</p><pre class="programlisting">@RequestMapping(value=<span class="hl-string">"/owners/{ownerId}"</span>, method=RequestMethod.GET)
<span class="hl-keyword">public</span> String findOwner(@PathVariable String ownerId, Model model) {
  Owner owner = ownerService.findOwner(ownerId);  
  model.addAttribute(<span class="hl-string">"owner"</span>, owner);  
  <span class="hl-keyword">return</span> <span class="hl-string">"displayOwner"</span>; 
}
</pre><p>The URI Template "<code class="literal">/owners/{ownerId}</code>"
        specifies the variable name <code class="literal">ownerId</code>. When the
        controller handles this request, the value of <code class="literal">ownerId</code> 
        is set to the value found in the appropriate segment of the URI.
        For example, when a request comes in for <code class="code">/owners/fred</code>, the value 
        <code class="literal">fred</code> is bound to the <code class="literal">ownerId</code> method argument.</p><div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Tip"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Tip]" src="images/tip.gif"></td><th align="left">Tip</th></tr><tr><td align="left" valign="top"><p>The matching of method parameter names to URI Template variable
	        names can only be done if your code is compiled with debugging
	        enabled. This is normally the case, however, if you do not have debugging enabled, 
	        you will need to specify the name of the URI Template variable as follows:</p><pre class="programlisting">@RequestMapping(value=<span class="hl-string">"/owners/{ownerId}"</span>, method=RequestMethod.GET)
<span class="hl-keyword">public</span> String findOwner(@PathVariable(<span class="hl-string">"ownerId"</span>) String ownerId, Model model) {
  <span class="hl-comment">// implementation omitted</span>
}</pre><p>You can do the same if you want the names of URI template variable and the method argument to differ:</p><pre class="programlisting">@RequestMapping(value=<span class="hl-string">"/owners/{ownerId}"</span>, method=RequestMethod.GET)
<span class="hl-keyword">public</span> String findOwner(@PathVariable(<span class="hl-string">"ownerId"</span>) String theOwner, Model model) {
  <span class="hl-comment">// implementation omitted</span>
}</pre></td></tr></table></div><p>A method can have multiple <code class="interfacename">@PathVariable</code> annotations:</p><pre class="programlisting">@RequestMapping(value=<span class="hl-string">"/owners/{ownerId}/pets/{petId}"</span>, method=RequestMethod.GET)
<span class="hl-keyword">public</span> String findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
  Owner owner = ownerService.findOwner(ownerId);  
  Pet pet = owner.getPet(petId);  
  model.addAttribute(<span class="hl-string">"pet"</span>, pet);  
  <span class="hl-keyword">return</span> <span class="hl-string">"displayPet"</span>; 
}
</pre><p>A URI template can be assembled from type and path level <span class="emphasis"><em>@RequestMapping</em></span> 
        annotations. As a result the <code class="methodname">findPet()</code> method can be invoked with a URL 
        such as <code class="filename">/owners/42/pets/21</code>.</p><pre class="programlisting">@Controller
@RequestMapping(<span class="hl-string">"/owners/{ownerId}"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> RelativePathUriTemplateController {

  @RequestMapping(<span class="hl-string">"/pets/{petId}"</span>)
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    
    <span class="hl-comment">// implementation omitted</span>
  }
}
</pre><p><code class="interfacename">@PathVariable</code> method arguments can be of
          <span class="bold"><strong>any simple type</strong></span> such as int, long, Date, etc. 
          Spring automatically converts to the appropriate type or throws a 
          <code class="classname">TypeMismatchException</code> if it fails to do so. 
          This type conversion process can be customized through a data binder. 
          See <a class="xref" href="mvc.html#mvc-ann-typeconversion" title="16.3.3.11&nbsp;Method Parameters And Type Conversion">Section&nbsp;16.3.3.11, &#8220;Method Parameters And Type Conversion&#8221;</a> and <a class="xref" href="mvc.html#mvc-ann-webdatabinder" title="16.3.3.12&nbsp;Customizing WebDataBinder initialization">Section&nbsp;16.3.3.12, &#8220;Customizing WebDataBinder
        initialization&#8221;</a>.
		</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-requestmapping-patterns"></a>16.3.2.2&nbsp;Path Patterns</h4></div></div></div><p>In addition to URI templates, the
        <code class="interfacename">@RequestMapping</code> annotation also
        supports Ant-style path patterns (for example,
        <code class="filename">/myPath/*.do</code>). A combination of URI templates and
        Ant-style globs is also supported (for example,
        <code class="filename">/owners/*/pets/{petId}</code>).</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-requestmapping-consumes"></a>16.3.2.3&nbsp;Consumable Media Types</h4></div></div></div><p>
        	You can narrow the primary mapping by specifying a list of consumable media types. 
        	The request will be matched only if the <span class="emphasis"><em>Content-Type</em></span> request header 
        	matches the specified media type. For example:
        </p><pre class="programlisting">@Controller
@RequestMapping(value = <span class="hl-string">"/pets"</span>, method = RequestMethod.POST, consumes=<span class="hl-string">"application/json"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">void</span> addPet(@RequestBody Pet pet, Model model) {    
    <span class="hl-comment">// implementation omitted</span>
}
</pre><p>
			Consumable media type expressions can also be negated as in <span class="emphasis"><em>!text/plain</em></span> 
			to match to all requests other than those with <span class="emphasis"><em>Content-Type</em></span> of 
			<span class="emphasis"><em>text/plain</em></span>. 
		</p><div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Tip"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Tip]" src="images/tip.gif"></td><th align="left">Tip</th></tr><tr><td align="left" valign="top"><p>The <span class="emphasis"><em>consumes</em></span> condition is supported on the type and on the 
			method level. Unlike most other conditions, when used at the type level, method-level 
			consumable types override rather than extend type-level consumeable types.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-requestmapping-produces"></a>16.3.2.4&nbsp;Producible Media Types</h4></div></div></div><p>
        	You can narrow the primary mapping by specifying a list of producible media types. 
        	The request will be matched only if the <span class="emphasis"><em>Accept</em></span> request header 
        	matches one of these values. Furthermore, use of the <span class="emphasis"><em>produces</em></span> 
        	condition ensures the actual content type used to generate the response respects 
        	the media types specified in the <span class="emphasis"><em>produces</em></span> condition.
        	For example:
        </p><pre class="programlisting">@Controller
@RequestMapping(value = <span class="hl-string">"/pets/{petId}"</span>, method = RequestMethod.GET, produces=<span class="hl-string">"application/json"</span>)
@ResponseBody
<span class="hl-keyword">public</span> Pet getPet(@PathVariable String petId, Model model) {    
    <span class="hl-comment">// implementation omitted</span>
}
</pre><p>
			Just like with <span class="emphasis"><em>consumes</em></span>, producible media type
			expressions can be negated as in <span class="emphasis"><em>!text/plain</em></span> to match 
			to all requests other than those with an <span class="emphasis"><em>Accept</em></span> header value of 
			<span class="emphasis"><em>text/plain</em></span>. 
        </p><div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Tip"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Tip]" src="images/tip.gif"></td><th align="left">Tip</th></tr><tr><td align="left" valign="top"><p>The <span class="emphasis"><em>produces</em></span> condition is supported on the type and on the method level. 
        	Unlike most other conditions, when used at the type level, method-level producible types
			override rather than extend type-level producible types.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-requestmapping-params-and-headers"></a>16.3.2.5&nbsp;Request Parameters and Header Values</h4></div></div></div><p>You can narrow request matching through request parameter conditions such as
        <code class="code">"myParam"</code>, <code class="code">"!myParam"</code>, or <code class="code">"myParam=myValue"</code>. 
        The first two test for request parameter presense/absence and the third for a specific parameter value.
        Here is an example with a request parameter value condition:</p><pre class="programlisting">@Controller
@RequestMapping(<span class="hl-string">"/owners/{ownerId}"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> RelativePathUriTemplateController {

  @RequestMapping(value = <span class="hl-string">"/pets/{petId}"</span>, method = RequestMethod.GET, params=<span class="hl-string">"myParam=myValue"</span>)
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    
    <span class="hl-comment">// implementation omitted</span>
  }
}
</pre><p>The same can be done to test for request header presence/absence or 
        to match based on a specific request header value:</p><pre class="programlisting">@Controller
@RequestMapping(<span class="hl-string">"/owners/{ownerId}"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> RelativePathUriTemplateController {

@RequestMapping(value = <span class="hl-string">"/pets"</span>, method = RequestMethod.GET, headers=<span class="hl-string">"myHeader=myValue"</span>)
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    
    <span class="hl-comment">// implementation omitted</span>
  }
}</pre><div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Tip"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Tip]" src="images/tip.gif"></td><th align="left">Tip</th></tr><tr><td align="left" valign="top"><p>Although you can match to <span class="emphasis"><em>Content-Type</em></span> and 
			<span class="emphasis"><em>Accept</em></span> header values using media type wildcards (for example
			<span class="emphasis"><em>"content-type=text/*"</em></span> will match to <span class="emphasis"><em>"text/plain"</em></span>
			and <span class="emphasis"><em>"text/html"</em></span>), it is recommended to use the
			<span class="emphasis"><em>consumes</em></span> and <span class="emphasis"><em>produces</em></span> conditions
			respectively instead. They are intended specifically for that purpose.
			</p></td></tr></table></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-ann-methods"></a>16.3.3&nbsp;Defining <span class="interface">@RequestMapping</span> handler methods</h3></div></div></div><p>An <code class="classname">@RequestMapping</code> handler method can have a very flexible
        signatures. The supported method arguments and return values are described in the
        following section. Most arguments can be used in arbitrary order with the only 
        exception of <code class="classname">BindingResult</code> arguments. This is described 
        in the next section.
      </p><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-arguments"></a>16.3.3.1&nbsp;Supported method argument types</h4></div></div></div><p>The following are the supported method arguments:
          </p><div class="itemizedlist"><ul type="disc"><li><p>Request or response objects (Servlet API). Choose any
              specific request or response type, for example
              <code class="interfacename">ServletRequest</code> or
              <code class="interfacename">HttpServletRequest</code>.</p></li><li><p>Session object (Servlet API): of type
              <code class="interfacename">HttpSession</code>. An argument of this
              type enforces the presence of a corresponding session. As a
              consequence, such an argument is never
              <code class="literal">null</code>.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>Session access may not be thread-safe, in particular in
                a Servlet environment. Consider setting the
                <code class="classname">AnnotationMethodHandlerAdapter</code>'s
                "synchronizeOnSession" flag to "true" if multiple requests are
                allowed to access a session concurrently.</p></td></tr></table></div></li><li><p><code class="classname">org.springframework.web.context.request.WebRequest</code>
              or
              <code class="classname">org.springframework.web.context.request.NativeWebRequest</code>.
              Allows for generic request parameter access as well as
              request/session attribute access, without ties to the native
              Servlet/Portlet API.</p></li><li><p><code class="classname">java.util.Locale</code> for the current
              request locale, determined by the most specific locale resolver
              available, in effect, the configured
              <code class="interfacename">LocaleResolver</code> in a Servlet
              environment.</p></li><li><p><code class="classname">java.io.InputStream</code> /
              <code class="classname">java.io.Reader</code> for access to the
              request's content. This value is the raw InputStream/Reader as
              exposed by the Servlet API.</p></li><li><p><code class="classname">java.io.OutputStream</code> /
              <code class="classname">java.io.Writer</code> for generating the
              response's content. This value is the raw OutputStream/Writer as
              exposed by the Servlet API.</p></li><li><p><code class="interfacename">java.security.Principal</code>
              containing the currently authenticated user.</p></li><li><p><code class="classname">@PathVariable</code> annotated parameters
              for access to URI template variables. See <a class="xref" href="mvc.html#mvc-ann-requestmapping-uri-templates" title="16.3.2.1&nbsp;URI Template Patterns">Section&nbsp;16.3.2.1, &#8220;URI Template Patterns&#8221;</a>.</p></li><li><p><code class="classname">@RequestParam</code> annotated parameters
              for access to specific Servlet request parameters. Parameter
              values are converted to the declared method argument type. See
              <a class="xref" href="mvc.html#mvc-ann-requestparam" title="16.3.3.3&nbsp;Binding request parameters to method parameters with @RequestParam">Section&nbsp;16.3.3.3, &#8220;Binding request parameters to method parameters with
        @RequestParam&#8221;</a>.</p></li><li><p><code class="interfacename">@RequestHeader</code> annotated parameters
              for access to specific Servlet request HTTP headers. Parameter
              values are converted to the declared method argument
              type.</p></li><li><p><code class="interfacename">@RequestBody</code> annotated parameters
              for access to the HTTP request body. Parameter values are
              converted to the declared method argument type using
              <code class="interfacename">HttpMessageConverter</code>s. See <a class="xref" href="mvc.html#mvc-ann-requestbody" title="16.3.3.4&nbsp;Mapping the request body with the @RequestBody annotation">Section&nbsp;16.3.3.4, &#8220;Mapping the request body with the @RequestBody
        annotation&#8221;</a>.</p></li><li><p><code class="classname">HttpEntity&lt;?&gt;</code> parameters
              for access to the Servlet request HTTP headers and contents. The request stream will be
              converted to the entity body using
              <code class="interfacename">HttpMessageConverter</code>s. See <a class="xref" href="mvc.html#mvc-ann-httpentity" title="16.3.3.6&nbsp;Using HttpEntity<?&gt;">Section&nbsp;16.3.3.6, &#8220;Using HttpEntity&lt;?&gt;&#8221;</a>.</p></li><li><p><code class="interfacename">java.util.Map</code> /
              <code class="interfacename">org.springframework.ui.Model</code> /
              <code class="classname">org.springframework.ui.ModelMap</code> for
              enriching the implicit model that is exposed to the web
              view.</p></li><li><p>Command or form objects to bind request parameters to bean
              properties (via setters) or directly to fields, with
              customizable type conversion, depending on
              <code class="classname">@InitBinder</code> methods and/or the
              HandlerAdapter configuration. See the
              <code class="literal">webBindingInitializer</code> property on
              <code class="classname">RequestMappingHandlerAdapter</code>. Such
              command objects along with their validation results will be
              exposed as model attributes by default, using the command class 
              class name - e.g. model attribute "orderAddress" for a command
              object of type "some.package.OrderAddress".
              The <code class="classname">ModelAttribute</code> annotation can be used
              on a method argument to customize the model attribute name used.</p></li><li><p><code class="classname">org.springframework.validation.Errors</code>
              /
              <code class="classname">org.springframework.validation.BindingResult</code>
              validation results for a preceding command or form object (the
              immediately preceding method argument).</p></li><li><p><code class="classname">org.springframework.web.bind.support.SessionStatus</code>
              status handle for marking form processing as complete, which
              triggers the cleanup of session attributes that have been
              indicated by the <code class="classname">@SessionAttributes</code>
              annotation at the handler type level.</p></li></ul></div><p>The <code class="interfacename">Errors</code> or
        <code class="interfacename">BindingResult</code> parameters have to follow
        the model object that is being bound immediately as the method
        signature might have more that one model object and Spring will create
        a separate <code class="interfacename">BindingResult</code> instance for
        each of them so the following sample won't work:</p><div class="example"><a name="d0e28669"></a><p class="title"><b>Example&nbsp;16.1.&nbsp;Invalid ordering of BindingResult and @ModelAttribute</b></p><div class="example-contents"><pre class="programlisting">@RequestMapping(method = RequestMethod.POST)
<span class="hl-keyword">public</span> String processSubmit(@ModelAttribute(<span class="hl-string">"pet"</span>) Pet pet,
    Model model, BindingResult result) { &#8230; }</pre><p>Note, that there is a <code class="interfacename">Model</code>
          parameter in between <code class="classname">Pet</code> and
          <code class="interfacename">BindingResult</code>. To get this working
          you have to reorder the parameters as follows:</p><pre class="programlisting">@RequestMapping(method = RequestMethod.POST)
<span class="hl-keyword">public</span> String processSubmit(@ModelAttribute(<span class="hl-string">"pet"</span>) Pet pet,
    BindingResult result, Model model) { &#8230; }</pre></div></div><br class="example-break"></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-return-types"></a>16.3.3.2&nbsp;Supported method return types</h4></div></div></div><p>The following are the supported return types:
          </p><div class="itemizedlist"><ul type="disc"><li><p>A <code class="classname">ModelAndView</code> object, with the
              model implicitly enriched with command objects and the results
              of <code class="literal">@ModelAttribute</code> annotated reference data
              accessor methods.</p></li><li><p>A <code class="interfacename">Model</code> object, with the
              view name implicitly determined through a
              <code class="interfacename">RequestToViewNameTranslator</code> and
              the model implicitly enriched with command objects and the
              results of <code class="literal">@ModelAttribute</code> annotated
              reference data accessor methods.</p></li><li><p>A <code class="interfacename">Map</code> object for exposing a
              model, with the view name implicitly determined through a
              <code class="interfacename">RequestToViewNameTranslator</code> and
              the model implicitly enriched with command objects and the
              results of <code class="literal">@ModelAttribute</code> annotated
              reference data accessor methods.</p></li><li><p>A <code class="interfacename">View</code> object, with the
              model implicitly determined through command objects and
              <code class="literal">@ModelAttribute</code> annotated reference data
              accessor methods. The handler method may also programmatically
              enrich the model by declaring a
              <code class="interfacename">Model</code> argument (see above).</p></li><li><p>A <code class="classname">String</code> value that is interpreted
              as the logical view name, with the model implicitly determined
              through command objects and <code class="literal">@ModelAttribute</code>
              annotated reference data accessor methods. The handler method
              may also programmatically enrich the model by declaring a
              <code class="interfacename">Model</code> argument (see
              above).</p></li><li><p><code class="literal">void</code> if the method handles the response
              itself (by writing the response content directly, declaring an
              argument of type <code class="interfacename">ServletResponse</code>
              / <code class="interfacename">HttpServletResponse</code> for that
              purpose) or if the view name is supposed to be implicitly
              determined through a
              <code class="interfacename">RequestToViewNameTranslator</code> (not
              declaring a response argument in the handler method
              signature).</p></li><li><p>If the method is annotated with
              <code class="interfacename">@ResponseBody</code>, the return type is
              written to the response HTTP body. The return value will be
              converted to the declared method argument type using
              <code class="interfacename">HttpMessageConverter</code>s. See <a class="xref" href="mvc.html#mvc-ann-responsebody" title="16.3.3.5&nbsp;Mapping the response body with the @ResponseBody annotation">Section&nbsp;16.3.3.5, &#8220;Mapping the response body with the @ResponseBody
        annotation&#8221;</a>.</p></li><li><p>A <code class="classname">HttpEntity&lt;?&gt;</code> or
              <code class="classname">ResponseEntity&lt;?&gt;</code> object
              to provide access to the Servlet response HTTP headers and
              contents. The entity body will be converted to the response
              stream using
              <code class="interfacename">HttpMessageConverter</code>s. See <a class="xref" href="mvc.html#mvc-ann-httpentity" title="16.3.3.6&nbsp;Using HttpEntity<?&gt;">Section&nbsp;16.3.3.6, &#8220;Using HttpEntity&lt;?&gt;&#8221;</a>.</p></li><li><p>Any other return type is considered to be a single model
              attribute to be exposed to the view, using the attribute name
              specified through <code class="literal">@ModelAttribute</code> at the
              method level (or the default attribute name based on the return
              type class name). The model is implicitly enriched with command
              objects and the results of <code class="literal">@ModelAttribute</code>
              annotated reference data accessor methods.</p></li></ul></div><p>
        </p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-requestparam"></a>16.3.3.3&nbsp;Binding request parameters to method parameters with
        <code class="interfacename">@RequestParam</code></h4></div></div></div><p>Use the <code class="classname">@RequestParam</code> annotation to bind
        request parameters to a method parameter in your controller.</p><p>The following code snippet shows the usage:</p><pre class="programlisting">@Controller
@RequestMapping(<span class="hl-string">"/pets"</span>)
@SessionAttributes(<span class="hl-string">"pet"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> EditPetForm {

    <span class="hl-comment">// ...</span>

    @RequestMapping(method = RequestMethod.GET)
    <span class="hl-keyword">public</span> String setupForm(@RequestParam(<span class="hl-string">"petId"</span>) <span class="hl-keyword">int</span> petId, ModelMap model) {
        Pet pet = <span class="hl-keyword">this</span>.clinic.loadPet(petId);
        model.addAttribute(<span class="hl-string">"pet"</span>, pet);
        <span class="hl-keyword">return</span> <span class="hl-string">"petForm"</span>;
    }

    <span class="hl-comment">// ...</span>
</pre><p>Parameters using this annotation are required by default, but
        you can specify that a parameter is optional by setting
        <code class="interfacename">@RequestParam</code>'s
        <code class="literal">required</code> attribute to <code class="literal">false</code>
        (e.g., <code class="literal">@RequestParam(value="id",
        required=false)</code>).</p><p>Type conversion is applied automatically if the target method parameter 
        type is not <code class="classname">String</code>.
        See <a class="xref" href="mvc.html#mvc-ann-typeconversion" title="16.3.3.11&nbsp;Method Parameters And Type Conversion">Section&nbsp;16.3.3.11, &#8220;Method Parameters And Type Conversion&#8221;</a>.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-requestbody"></a>16.3.3.4&nbsp;Mapping the request body with the @RequestBody
        annotation</h4></div></div></div><p>The <code class="classname">@RequestBody</code> method parameter
        annotation indicates that a method parameter should be bound to the
        value of the HTTP request body. For example:</p><pre class="programlisting">@RequestMapping(value = <span class="hl-string">"/something"</span>, method = RequestMethod.PUT)
<span class="hl-keyword">public</span> <span class="hl-keyword">void</span> handle(@RequestBody String body, Writer writer) <span class="hl-keyword">throws</span> IOException {
  writer.write(body);
}</pre><p>You convert the request body to the method argument by using an
        <code class="interfacename">HttpMessageConverter</code>.
        <code class="interfacename">HttpMessageConverter</code> is responsible for
        converting from the HTTP request message to an object and converting
        from an object to the HTTP response body.
        The <code class="classname">RequestMappingHandlerAdapter</code> supports the 
        <code class="classname">@RequestBody</code> annotation with the following default 
        <code class="interfacename">HttpMessageConverters</code>:</p><div class="itemizedlist"><ul type="disc"><li><p><code class="classname">ByteArrayHttpMessageConverter</code>
            converts byte arrays.</p></li><li><p><code class="classname">StringHttpMessageConverter</code> converts
            strings.</p></li><li><p><code class="classname">FormHttpMessageConverter</code> converts
            form data to/from a MultiValueMap&lt;String, String&gt;.</p></li><li><p><code class="classname">SourceHttpMessageConverter</code> converts
            to/from a javax.xml.transform.Source.</p></li></ul></div><p>For more information on these converters, see <a class="link" href="remoting.html#rest-message-conversion" title="20.9.2&nbsp;HTTP Message Conversion">Message Converters</a>. Also note
        that if using the MVC namespace, a wider range of message converters 
        are registered by default. See <a class="xref" href="mvc.html#mvc-annotation-driven" title="16.12.1&nbsp;mvc:annotation-driven">Section&nbsp;16.12.1, &#8220;mvc:annotation-driven&#8221;</a> 
        for more information.</p><p>If you intend to read and write XML, you will need to configure the 
        <code class="classname">MarshallingHttpMessageConverter</code> with a 
        specific <code class="interfacename">Marshaller</code> and 
        an <code class="interfacename">Unmarshaller</code> implementation from the
        <code class="classname">org.springframework.oxm</code> package.
        For example:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"messageConverters"</span>&gt;
      &lt;<span class="hl-tag">util:list</span> <span class="hl-attribute">id</span>=<span class="hl-value">"beanList"</span>&gt;
        &lt;<span class="hl-tag">ref</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"stringHttpMessageConverter"</span>/&gt;
        &lt;<span class="hl-tag">ref</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"marshallingHttpMessageConverter"</span>/&gt;
      &lt;<span class="hl-tag">/util:list</span>&gt;
    &lt;<span class="hl-tag">/property
&lt;/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"stringHttpMessageConverter"</span> 
       <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.http.converter.StringHttpMessageConverter"</span>/&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"marshallingHttpMessageConverter"</span> 
      <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.http.converter.xml.MarshallingHttpMessageConverter"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"marshaller"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"castorMarshaller"</span> /&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"unmarshaller"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"castorMarshaller"</span> /&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"castorMarshaller"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.oxm.castor.CastorMarshaller"</span>/&gt;
</pre><p>An <code class="classname">@RequestBody</code> method parameter can be annotated with 
        <code class="classname">@Valid</code>, in which case it will validated using the configured
        <code class="classname">Validator</code> instance. When using the MVC namespace a JSR-303 
        validator is configured automatically assuming a JSR-303 implementation is available 
        on the classpath. If validation fails a <code class="classname">RequestBodyNotValidException</code>
        is raised. The exception is handled by the <code class="classname">DefaultHandlerExceptionResolver</code>
        and results in a <code class="literal">500</code> error send back to the client along with
        a message containing the validation errors.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p> Also see <a class="xref" href="mvc.html#mvc-annotation-driven" title="16.12.1&nbsp;mvc:annotation-driven">Section&nbsp;16.12.1, &#8220;mvc:annotation-driven&#8221;</a> for information on 
          configuring message converters and a validator through the MVC namespace.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-responsebody"></a>16.3.3.5&nbsp;Mapping the response body with the <code class="interfacename">@ResponseBody</code>
        annotation</h4></div></div></div><p>The <code class="interfacename">@ResponseBody</code> annotation is
        similar to <code class="interfacename">@RequestBody</code>. This
        annotation can be put on a method and
        indicates that the return type should be written straight to the HTTP
        response body (and not placed in a Model, or interpreted as a view
        name). For example:</p><pre class="programlisting">@RequestMapping(value = <span class="hl-string">"/something"</span>, method = RequestMethod.PUT)
@ResponseBody
<span class="hl-keyword">public</span> String helloWorld()  {
  <span class="hl-keyword">return</span> <span class="hl-string">"Hello World"</span>;
}</pre><p>The above example will result in the text <code class="literal">Hello
        World</code> being written to the HTTP response stream.</p><p>As with <code class="interfacename">@RequestBody</code>, Spring
        converts the returned object to a response body by using an
        <code class="interfacename">HttpMessageConverter</code>. For more
        information on these converters, see the previous section and <a class="link" href="remoting.html#rest-message-conversion" title="20.9.2&nbsp;HTTP Message Conversion">Message Converters</a>.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-httpentity"></a>16.3.3.6&nbsp;Using <code class="classname">HttpEntity&lt;?&gt;</code></h4></div></div></div><p>The <code class="classname">HttpEntity</code> is similar to
        <code class="interfacename">@RequestBody</code> and
        <code class="interfacename">@ResponseBody</code>. Besides getting
        access to the request and response body, <code class="classname">HttpEntity</code>
        (and the response-specific subclass <code class="classname">ResponseEntity</code>)
        also allows access to the request and response headers, like so:</p><pre class="programlisting">@RequestMapping(<span class="hl-string">"/something"</span>)
<span class="hl-keyword">public</span> ResponseEntity&lt;String&gt; handle(HttpEntity&lt;<span class="hl-keyword">byte</span>[]&gt; requestEntity) <span class="hl-keyword">throws</span> UnsupportedEncodingException {
  String requestHeader = requestEntity.getHeaders().getFirst(<span class="hl-string">"MyRequestHeader"</span>));
  <span class="hl-keyword">byte</span>[] requestBody = requestEntity.getBody();
  <span class="hl-comment">// do something with request header and body</span>

  HttpHeaders responseHeaders = <span class="hl-keyword">new</span> HttpHeaders();
  responseHeaders.set(<span class="hl-string">"MyResponseHeader"</span>, <span class="hl-string">"MyValue"</span>);
  <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> ResponseEntity&lt;String&gt;(<span class="hl-string">"Hello World"</span>, responseHeaders, HttpStatus.CREATED);
}</pre><p>The above example gets the value of the <code class="literal">MyRequestHeader</code> request
        header, and reads the body as a byte array. It adds the <code class="literal">MyResponseHeader</code>
        to the response, writes <code class="literal">Hello World</code> to the response
        stream, and sets the response status code to 201 (Created).</p><p>As with <code class="interfacename">@RequestBody</code> and
        <code class="interfacename">@ResponseBody</code>, Spring
        uses <code class="interfacename">HttpMessageConverter</code> to convert
        from and to the request and response streams. For more
        information on these converters, see the previous section and <a class="link" href="remoting.html#rest-message-conversion" title="20.9.2&nbsp;HTTP Message Conversion">Message Converters</a>.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-modelattrib"></a>16.3.3.7&nbsp;Command and Form Objects</h4></div></div></div><p>The <code class="classname">@ModelAttribute</code> annotation is central to 
        working with command and form objects. It has a couple of usage scenarios
        described in this section.
        </p><p>The main scenario is using <code class="classname">@ModelAttribute</code> on
        a method parameter in order to get access to data received from a form submission
        or from request parameters. For example an object of type 
        <code class="classname">Person</code> with fields <code class="literal">firstName</code>
        and <code class="literal">lastName</code> will be populated accordingly assuming
        the presence of either form or query string parameters with matching names:
        e.g. <code class="literal">firstName=Rod</code> and <code class="literal">lastName=Johnson</code>.
        Below is an example of a <code class="classname">@ModelAttribute</code>-annotated 
        method parameter.</p><pre class="programlisting">@Controller
@RequestMapping(<span class="hl-string">"/owners/{ownerId}/pets/{petId}/edit"</span>)
@SessionAttributes(<span class="hl-string">"pet"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> EditPetForm {

    @RequestMapping(method = RequestMethod.POST)
    <span class="hl-keyword">public</span> String processSubmit(
            @ModelAttribute(<span class="hl-string">"pet"</span>) Pet pet,
            BindingResult result, SessionStatus status) {

    }

}</pre><p>Before invoking the method, Spring MVC will create a <code class="classname">Pet</code> 
        instance, populate it using request parameters, and also add it to the model 
        under the name <code class="literal">pet</code>.
        The <code class="classname">Pet</code> instance may have been created using the
        default constructor (if available), it may have been obtained from the HTTP session in
        conjunction with use of <code class="classname">@SessionAttributes</code> (see the next section), or
        it may have been created by another <code class="classname">@ModelAttribute</code>-annotated method 
        in the same class. A <code class="classname">@ModelAttribute</code>-annotated method 
        is the second scenario for using the annotation.</p><p>When used at the method level a <code class="classname">@ModelAttribute</code> 
        contributes one or more objects to the model. See the <code class="literal">populatePetTypes()</code> 
        method in the following example:</p><pre class="programlisting">@Controller
@RequestMapping(<span class="hl-string">"/owners/{ownerId}/pets/{petId}/edit"</span>)
@SessionAttributes(<span class="hl-string">"pet"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> EditPetForm {

    <span class="hl-comment">// ...</span>

    @ModelAttribute(<span class="hl-string">"types"</span>)
    <span class="hl-keyword">public</span> Collection&lt;PetType&gt; populatePetTypes() {
        <span class="hl-keyword">return</span> <span class="hl-keyword">this</span>.clinic.getPetTypes();
    }

    @RequestMapping(method = RequestMethod.POST)
    <span class="hl-keyword">public</span> String processSubmit(
            @ModelAttribute(<span class="hl-string">"pet"</span>) Pet pet,
            BindingResult result, SessionStatus status) {

        <span class="hl-keyword">new</span> PetValidator().validate(pet, result);
        <span class="hl-keyword">if</span> (result.hasErrors()) {
            <span class="hl-keyword">return</span> <span class="hl-string">"petForm"</span>;
        }
        <span class="hl-keyword">else</span> {
            <span class="hl-keyword">this</span>.clinic.storePet(pet);
            status.setComplete();
            <span class="hl-keyword">return</span> <span class="hl-string">"redirect:owner.do?ownerId="</span> + pet.getOwner().getId();
        }
    }

}</pre><p><code class="classname">@ModelAttribute</code> methods are
        executed <span class="emphasis"><em>before</em></span> the chosen
        <code class="classname">@RequestMapping</code> annotated handler method.
        They effectively pre-populate the model with specific
        attributes, often loaded from a database. Such an attribute can then
        be accessed through a <code class="classname">@ModelAttribute</code>-annotated
        <code class="classname">@RequestMapping</code> parameter.
        An <code class="classname">@ModelAttribute</code> method can contain the same 
        method arguments as documented previously for 
        <code class="classname">@RequestMapping</code> methods.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-sessionattrib"></a>16.3.3.8&nbsp;Specifying attributes to store in a session with
        <code class="classname">@SessionAttributes</code></h4></div></div></div><p>The type-level <code class="classname">@SessionAttributes</code>
        annotation declares session attributes used by a specific handler.
        This will typically list the names of model attributes or types of
        model attributes which should be transparently stored in the session
        or some conversational storage, serving as form-backing beans between
        subsequent requests.</p><p>The following code snippet shows the usage of this annotation,
        specifying the model attribute name:</p><pre class="programlisting">@Controller
@RequestMapping(<span class="hl-string">"/editPet.do"</span>)
@SessionAttributes(<span class="hl-string">"pet"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> EditPetForm {
    <span class="hl-comment">// ...</span>
}</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>When using controller interfaces (e.g. for AOP proxying), make sure to
          consistently put <span class="emphasis"><em>all</em></span> your mapping annotations - such as
          <code class="interfacename">@RequestMapping</code> and
          <code class="interfacename">@SessionAttributes</code> - on the controller
          <span class="emphasis"><em>interface</em></span> rather than on the implementation class.
          </p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-cookievalue"></a>16.3.3.9&nbsp;Mapping cookie values with the @CookieValue annotation</h4></div></div></div><p>The <code class="interfacename">@CookieValue</code> annotation
        allows a method parameter to be bound to the value of an HTTP
        cookie.</p><p>Let us consider that the following cookie has been received with
        an http request:</p><pre class="programlisting">JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84</pre><p>The following code sample demonstrates how to get the value of
        the <code class="literal">JSESSIONID</code> cookie:</p><pre class="programlisting">@RequestMapping(<span class="hl-string">"/displayHeaderInfo.do"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">void</span> displayHeaderInfo(@CookieValue(<span class="hl-string">"JSESSIONID"</span>) String cookie)  {

  <span class="hl-comment">//...</span>

}</pre><p>Type conversion is applied automatically if the target method 
        parameter type is not <code class="classname">String</code>.
        See <a class="xref" href="mvc.html#mvc-ann-typeconversion" title="16.3.3.11&nbsp;Method Parameters And Type Conversion">Section&nbsp;16.3.3.11, &#8220;Method Parameters And Type Conversion&#8221;</a>.</p><p>This annotation is supported for annotated handler methods in
        Servlet and Portlet environments.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-requestheader"></a>16.3.3.10&nbsp;Mapping request header attributes with the @RequestHeader
        annotation</h4></div></div></div><p>The <code class="interfacename">@RequestHeader</code> annotation
        allows a method parameter to be bound to a request header.</p><p>Here is a sample request header:</p><pre class="programlisting">
Host                    localhost:8080
Accept                  text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language         fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding         gzip,deflate
Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive              300
</pre><p>The following code sample demonstrates how to get the value of
        the <code class="literal">Accept-Encoding</code> and
        <code class="literal">Keep-Alive</code> headers:</p><pre class="programlisting">@RequestMapping(<span class="hl-string">"/displayHeaderInfo.do"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">void</span> displayHeaderInfo(@RequestHeader(<span class="hl-string">"Accept-Encoding"</span>) String encoding,
                              @RequestHeader(<span class="hl-string">"Keep-Alive"</span>) <span class="hl-keyword">long</span> keepAlive)  {

  <span class="hl-comment">//...</span>

}</pre><p>Type conversion is applied automatically if the method parameter 
        is not <code class="classname">String</code>. 
        See <a class="xref" href="mvc.html#mvc-ann-typeconversion" title="16.3.3.11&nbsp;Method Parameters And Type Conversion">Section&nbsp;16.3.3.11, &#8220;Method Parameters And Type Conversion&#8221;</a>.</p><div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Tip"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Tip]" src="images/tip.gif"></td><th align="left">Tip</th></tr><tr><td align="left" valign="top"><p>Built-in support is available for converting a comma-separated 
        string into an array/collection of strings or other types known to the 
        type conversion system. For example a method parameter annotated with 
        <code class="literal">@RequestHeader("Accept")</code> may be of type 
        <code class="classname">String</code> but also <code class="classname">String[]</code> 
        or <code class="classname">List&lt;String&gt;</code>.</p></td></tr></table></div><p>This annotation is supported for annotated handler methods in
        Servlet and Portlet environments.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-typeconversion"></a>16.3.3.11&nbsp;Method Parameters And Type Conversion</h4></div></div></div><p>String-based values extracted from the request including
        request parameters, path variables, request headers, and cookie values 
        may need to be converted to the target type of the method parameter or 
        field (e.g. binding a request parameter to a field in an  
        <code class="interfacename">@ModelAttribute</code> parameter) they're bound to. 
        If the target type is not <code class="classname">String</code>, Spring 
        automatically converts to the appropriate type. 
        All simple types such as int, long, Date, etc. are 
        supported. You can further customize the conversion process 
        through a <code class="classname">WebDataBinder</code>  
        (see <a class="xref" href="mvc.html#mvc-ann-webdatabinder" title="16.3.3.12&nbsp;Customizing WebDataBinder initialization">Section&nbsp;16.3.3.12, &#8220;Customizing WebDataBinder
        initialization&#8221;</a>) or by registering 
        <code class="classname">Formatters</code> with the 
        <code class="classname">FormattingConversionService</code>
        (see <a class="xref" href="validation.html#format" title="6.6&nbsp;Spring 3 Field Formatting">Section&nbsp;6.6, &#8220;Spring 3 Field Formatting&#8221;</a>).</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-ann-webdatabinder"></a>16.3.3.12&nbsp;Customizing <code class="classname">WebDataBinder</code>
        initialization</h4></div></div></div><p>To customize request parameter binding with PropertyEditors
        through Spring's <code class="classname">WebDataBinder</code>, you can use
        either <code class="interfacename">@InitBinder</code>-annotated methods
        within your controller or externalize your configuration by providing
        a custom <code class="interfacename">WebBindingInitializer</code>.</p><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="mvc-ann-initbinder"></a>Customizing data binding with
          <code class="interfacename">@InitBinder</code></h5></div></div></div><p>Annotating controller methods with
          <code class="interfacename">@InitBinder</code> allows you to configure
          web data binding directly within your controller class.
          <code class="interfacename">@InitBinder</code> identifies methods that
          initialize the <code class="classname">WebDataBinder</code> that will be
          used to populate command and form object arguments of annotated
          handler methods.</p><p>Such init-binder methods support all arguments that
          <code class="interfacename">@RequestMapping</code> supports, except for
          command/form objects and corresponding validation result objects.
          Init-binder methods must not have a return value. Thus, they are
          usually declared as <code class="literal">void</code>. Typical arguments
          include <code class="classname">WebDataBinder</code> in combination with
          <code class="interfacename">WebRequest</code> or
          <code class="classname">java.util.Locale</code>, allowing code to register
          context-specific editors.</p><p>The following example demonstrates the use of
          <code class="interfacename">@InitBinder</code> to configure a
          <code class="classname">CustomDateEditor</code> for all
          <code class="classname">java.util.Date</code> form properties.</p><pre class="programlisting">@Controller
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MyFormController {

    @InitBinder
    <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = <span class="hl-keyword">new</span> SimpleDateFormat(<span class="hl-string">"yyyy-MM-dd"</span>);
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.<span class="hl-keyword">class</span>, <span class="hl-keyword">new</span> CustomDateEditor(dateFormat, false));
    }

    <span class="hl-comment">// ...</span>
}</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="mvc-ann-webbindinginitializer"></a>Configuring a custom
          <code class="interfacename">WebBindingInitializer</code></h5></div></div></div><p>To externalize data binding initialization, you can provide a
          custom implementation of the
          <code class="interfacename">WebBindingInitializer</code> interface,
          which you then enable by supplying a custom bean configuration for
          an <code class="classname">AnnotationMethodHandlerAdapter</code>, thus
          overriding the default configuration.</p><p>The following example from the PetClinic application shows a
          configuration using a custom implementation of the
          <code class="interfacename">WebBindingInitializer</code> interface,
          <code class="classname">org.springframework.samples.petclinic.web.ClinicBindingInitializer</code>,
          which configures PropertyEditors required by several of the
          PetClinic controllers.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"cacheSeconds"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"0"</span> /&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"webBindingInitializer"</span>&gt;
        &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.samples.petclinic.web.ClinicBindingInitializer"</span> /&gt;
    &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;
</pre></div></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="mvc-handlermapping"></a>16.4&nbsp;Handler mappings</h2></div></div></div><p>In previous versions of Spring, users were required to define one 
    or more <code class="interfacename">HandlerMapping</code> beans in the web application
    context to map incoming web requests to appropriate handlers. With the
    introduction of annotated controllers, you generally don't need to do 
    that because the <code class="classname">RequestMappingHandlerMapping</code> 
    automatically looks for <code class="interfacename">@RequestMapping</code> 
    annotations on all <code class="interfacename">@Controller</code> beans. 
    However, do keep in mind that all <code class="classname">HandlerMapping</code>
    classes extending from <code class="classname">AbstractHandlerMapping</code> 
    have the following properties that you can use to customize their behavior:
    </p><div class="variablelist"><dl><dt><span class="term"><code class="literal">interceptors</code></span></dt><dd><p>List of interceptors to use.
          <code class="interfacename">HandlerInterceptor</code>s are discussed in
          <a class="xref" href="mvc.html#mvc-handlermapping-interceptor" title="16.4.1&nbsp;Intercepting requests with a HandlerInterceptor">Section&nbsp;16.4.1, &#8220;Intercepting requests with a
      HandlerInterceptor&#8221;</a>.</p></dd><dt><span class="term"><code class="literal">defaultHandler</code></span></dt><dd><p>Default handler to use, when this handler mapping does not
          result in a matching handler.</p></dd><dt><span class="term"><code class="literal">order</code></span></dt><dd><p>Based on the value of the order property (see the
          <code class="literal">org.springframework.core.Ordered</code> interface),
          Spring sorts all handler mappings available in the context and
          applies the first matching handler.</p></dd><dt><span class="term"><code class="literal">alwaysUseFullPath</code></span></dt><dd><p>If <code class="literal">true</code> , Spring uses the full path within
          the current servlet context to find an appropriate handler. If
          <code class="literal">false</code> (the default), the path within the current
          servlet mapping is used. For example, if a servlet is mapped using
          <code class="literal">/testing/*</code> and the
          <code class="literal">alwaysUseFullPath</code> property is set to true,
          <code class="literal">/testing/viewPage.html</code> is used, whereas if the
          property is set to false, <code class="literal">/viewPage.html</code> is
          used.</p></dd><dt><span class="term"><code class="literal">urlDecode</code></span></dt><dd><p>Defaults to <code class="literal">true</code>, as of Spring 2.5. 
          If you prefer to compare encoded paths, set this flag to
          <code class="literal">false</code>. However, the
          <code class="interfacename">HttpServletRequest</code> always exposes the
          servlet path in decoded form. Be aware that the servlet path will
          not match when compared with encoded paths.</p></dd></dl></div><p>The following example shows how to configure an interceptor:</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;
  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"handlerMapping"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"interceptors"</span>&gt;
      &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.MyInterceptor"</span>/&gt;
    &lt;<span class="hl-tag">/property</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">beans</span>&gt;</pre><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-handlermapping-interceptor"></a>16.4.1&nbsp;Intercepting requests with a
      <code class="interfacename">HandlerInterceptor</code></h3></div></div></div><p>Spring's handler mapping mechanism includes handler interceptors,
      which are useful when you want to apply specific functionality to
      certain requests, for example, checking for a principal.</p><p>Interceptors located in the handler mapping must implement
      <code class="interfacename">HandlerInterceptor</code> from the
      <code class="literal">org.springframework.web.servlet</code> package. This
      interface defines three methods: <code class="literal">preHandle(..)</code> 
      is called <span class="emphasis"><em>before</em></span> the actual handler is executed; 
      <code class="literal">postHandle(..)</code> is called <span class="emphasis"><em>after</em></span> 
      the handler is executed; and <code class="literal">afterCompletion(..)</code> is
      called <span class="emphasis"><em>after the complete request has finished</em></span>.
      These three methods should provide enough flexibility to do all kinds of
      preprocessing and postprocessing.</p><p>The <code class="literal">preHandle(..)</code> method returns a boolean
      value. You can use this method to break or continue the processing of
      the execution chain. When this method returns <code class="literal">true</code>,
      the handler execution chain will continue; when it returns false, the
      <code class="classname">DispatcherServlet</code> assumes the interceptor itself
      has taken care of requests (and, for example, rendered an appropriate
      view) and does not continue executing the other interceptors and the
      actual handler in the execution chain.</p><p>Interceptors can be configured using the <code class="literal">interceptors</code>
      property, which is present on all <code class="classname">HandlerMapping</code> classes 
      extending from <code class="classname">AbstractHandlerMapping</code>.
      This is shown in the example below:</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;
    &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"handlerMapping"</span>
          <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"</span>&gt;
        &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"interceptors"</span>&gt;
            &lt;<span class="hl-tag">list</span>&gt;
                &lt;<span class="hl-tag">ref</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"officeHoursInterceptor"</span>/&gt;
            &lt;<span class="hl-tag">/list</span>&gt;
        &lt;<span class="hl-tag">/property</span>&gt;
    &lt;<span class="hl-tag">/bean</span>&gt;

    &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"officeHoursInterceptor"</span>
          <span class="hl-attribute">class</span>=<span class="hl-value">"samples.TimeBasedAccessInterceptor"</span>&gt;
        &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"openingTime"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"9"</span>/&gt;
        &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"closingTime"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"18"</span>/&gt;
    &lt;<span class="hl-tag">/bean</span>&gt;
&lt;<span class="hl-tag">beans</span>&gt;</pre><pre class="programlisting"><span class="hl-keyword">package</span> samples;

<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> TimeBasedAccessInterceptor <span class="hl-keyword">extends</span> HandlerInterceptorAdapter {

    <span class="hl-keyword">private</span> <span class="hl-keyword">int</span> openingTime;
    <span class="hl-keyword">private</span> <span class="hl-keyword">int</span> closingTime;

    <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setOpeningTime(<span class="hl-keyword">int</span> openingTime) {
        <span class="hl-keyword">this</span>.openingTime = openingTime;
    }

    <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setClosingTime(<span class="hl-keyword">int</span> closingTime) {
        <span class="hl-keyword">this</span>.closingTime = closingTime;
    }

    <span class="hl-keyword">public</span> <span class="hl-keyword">boolean</span> preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) <span class="hl-keyword">throws</span> Exception {

        Calendar cal = Calendar.getInstance();
        <span class="hl-keyword">int</span> hour = cal.get(HOUR_OF_DAY);
        <span class="hl-keyword">if</span> (openingTime &lt;= hour &lt; closingTime) {
            <span class="hl-keyword">return</span> true;
        } <span class="hl-keyword">else</span> {
            response.sendRedirect(<span class="hl-string">"http://host.com/outsideOfficeHours.html"</span>);
            <span class="hl-keyword">return</span> false;
        }
    }
}</pre><p>Any request handled by this mapping is intercepted by the
      <code class="classname">TimeBasedAccessInterceptor</code>. If the current time
      is outside office hours, the user is redirected to a static HTML file
      that says, for example, you can only access the website during office
      hours.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>When using the <code class="classname">RequestMappingHandlerMapping</code>
        the actual handler is an instance of <code class="classname">HandlerMethod</code>
        which identifies the specific controller method that will be invoked.
        </p></td></tr></table></div><p>As you can see, the Spring adapter class
      <code class="classname">HandlerInterceptorAdapter</code> makes it easier to
      extend the <code class="interfacename">HandlerInterceptor</code>
      interface.</p><div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Tip"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Tip]" src="images/tip.gif"></td><th align="left">Tip</th></tr><tr><td align="left" valign="top"><p>In the example above, the configured interceptor will apply to all
        requests handled with annotated controller methods. If you want to narrow
        down the URL paths to which an interceptor applies, you can use the MVC
        namespace to do that. See <a class="xref" href="mvc.html#mvc-annotation-driven" title="16.12.1&nbsp;mvc:annotation-driven">Section&nbsp;16.12.1, &#8220;mvc:annotation-driven&#8221;</a>.</p></td></tr></table></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="mvc-viewresolver"></a>16.5&nbsp;Resolving views</h2></div></div></div><p>All MVC frameworks for web applications provide a way to address
    views. Spring provides view resolvers, which enable you to render models
    in a browser without tying you to a specific view technology. Out of the
    box, Spring enables you to use JSPs, Velocity templates and XSLT views,
    for example. See <a class="xref" href="view.html" title="17.&nbsp;View technologies">Chapter&nbsp;17, <i>View technologies</i></a> for a discussion of how to
    integrate and use a number of disparate view technologies.</p><p>The two interfaces that are important to the way Spring handles
    views are <code class="interfacename">ViewResolver</code> and
    <code class="interfacename">View</code>. The
    <code class="interfacename">ViewResolver</code> provides a mapping between
    view names and actual views. The <code class="interfacename">View</code>
    interface addresses the preparation of the request and hands the request
    over to one of the view technologies.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-viewresolver-resolver"></a>16.5.1&nbsp;Resolving views with the
      <code class="interfacename">ViewResolver</code> interface</h3></div></div></div><p>As discussed in <a class="xref" href="mvc.html#mvc-controller" title="16.3&nbsp;Implementing Controllers">Section&nbsp;16.3, &#8220;Implementing Controllers&#8221;</a>, all handler
      methods in the Spring Web MVC controllers must resolve to a logical view
      name, either explicitly (e.g., by returning a <code class="literal">String</code>,
      <code class="literal">View</code>, or <code class="literal">ModelAndView</code>) or
      implicitly (i.e., based on conventions). Views in Spring are addressed
      by a logical view name and are resolved by a view resolver. Spring comes
      with quite a few view resolvers. This table lists most of them; a couple
      of examples follow.</p><div class="table"><a name="mvc-view-resolvers-tbl"></a><p class="title"><b>Table&nbsp;16.3.&nbsp;View resolvers</b></p><div class="table-contents"><table summary="View resolvers" style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="interfacename">ViewResolver</code></th><th style="border-bottom: 1.0pt solid ; ">Description</th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">AbstractCachingViewResolver</code></td><td style="border-bottom: 1.0pt solid ; ">Abstract view resolver that caches views. Often views
              need preparation before they can be used; extending this view
              resolver provides caching.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">XmlViewResolver</code></td><td style="border-bottom: 1.0pt solid ; ">Implementation of
              <code class="interfacename">ViewResolver</code> that accepts a
              configuration file written in XML with the same DTD as Spring's
              XML bean factories. The default configuration file is
              <code class="literal">/WEB-INF/views.xml</code>.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">ResourceBundleViewResolver</code></td><td style="border-bottom: 1.0pt solid ; ">Implementation of
              <code class="interfacename">ViewResolver</code> that uses bean
              definitions in a <code class="classname">ResourceBundle</code>,
              specified by the bundle base name. Typically you define the
              bundle in a properties file, located in the classpath. The
              default file name is
              <code class="literal">views.properties</code>.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">UrlBasedViewResolver</code></td><td style="border-bottom: 1.0pt solid ; ">Simple implementation of the
              <code class="interfacename">ViewResolver</code> interface that
              effects the direct resolution of logical view names to URLs,
              without an explicit mapping definition. This is appropriate if
              your logical names match the names of your view resources in a
              straightforward manner, without the need for arbitrary
              mappings.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">InternalResourceViewResolver</code></td><td style="border-bottom: 1.0pt solid ; ">Convenient subclass of
              <code class="classname">UrlBasedViewResolver</code> that supports
              <code class="classname">InternalResourceView</code> (in effect, Servlets
              and JSPs) and subclasses such as <code class="classname">JstlView</code>
              and <code class="classname">TilesView</code>. You can specify the view
              class for all views generated by this resolver by using
              <code class="literal">setViewClass(..)</code>. See the Javadocs for the
              <code class="classname">UrlBasedViewResolver</code> class for
              details.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">VelocityViewResolver</code> /
              <code class="classname">FreeMarkerViewResolver</code></td><td style="border-bottom: 1.0pt solid ; ">Convenient subclass of
              <code class="classname">UrlBasedViewResolver</code> that supports
              <code class="classname">VelocityView</code> (in effect, Velocity
              templates) or <code class="classname">FreeMarkerView</code>
              ,respectively, and custom subclasses of them.</td></tr><tr><td style="border-right: 1.0pt solid ; "><code class="classname">ContentNegotiatingViewResolver</code></td><td style="">Implementation of the
              <code class="interfacename">ViewResolver</code> interface that
              resolves a view based on the request file name or
              <code class="literal">Accept</code> header. See <a class="xref" href="mvc.html#mvc-multiple-representations" title="16.5.4&nbsp;ContentNegotiatingViewResolver">Section&nbsp;16.5.4, &#8220;ContentNegotiatingViewResolver&#8221;</a>.</td></tr></tbody></table></div></div><br class="table-break"><p>As an example, with JSP as a view technology, you can use the
      <code class="classname">UrlBasedViewResolver</code>. This view resolver
      translates a view name to a URL and hands the request over to the
      RequestDispatcher to render the view.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"viewResolver"</span>
      <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.view.UrlBasedViewResolver"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"viewClass"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"org.springframework.web.servlet.view.JstlView"</span>/&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"prefix"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"/WEB-INF/jsp/"</span>/&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"suffix"</span> <span class="hl-attribute">value</span>=<span class="hl-value">".jsp"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>When returning <code class="literal">test</code> as a logical view name,
      this view resolver forwards the request to the
      <code class="classname">RequestDispatcher</code> that will send the request to
      <code class="literal">/WEB-INF/jsp/test.jsp</code>.</p><p>When you combine different view technologies in a web application,
      you can use the
      <code class="classname">ResourceBundleViewResolver</code>:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"viewResolver"</span>
      <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.view.ResourceBundleViewResolver"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"basename"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"views"</span>/&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"defaultParentView"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"parentView"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The <code class="classname">ResourceBundleViewResolver</code> inspects the
      <code class="classname">ResourceBundle</code> identified by the basename, and
      for each view it is supposed to resolve, it uses the value of the
      property <code class="literal">[viewname].(class)</code> as the view class and the
      value of the property <code class="literal">[viewname].url</code> as the view url.
      Examples can be found in the next chapter which covers view
      technologies. As you can see, you can identify a parent view, from which
      all views in the properties file &#8220;<span class="quote">extend</span>&#8221;. This way you can
      specify a default view class, for example.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>Subclasses of <code class="classname">AbstractCachingViewResolver</code>
        cache view instances that they resolve. Caching improves performance
        of certain view technologies. It's possible to turn off the cache by
        setting the <code class="literal">cache</code> property to
        <code class="literal">false</code>. Furthermore, if you must refresh a certain
        view at runtime (for example when a Velocity template is modified),
        you can use the <code class="literal">removeFromCache(String viewName, Locale
        loc)</code> method.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-viewresolver-chaining"></a>16.5.2&nbsp;Chaining ViewResolvers</h3></div></div></div><p>Spring supports multiple view resolvers. Thus you can chain
      resolvers and, for example, override specific views in certain
      circumstances. You chain view resolvers by adding more than one resolver
      to your application context and, if necessary, by setting the
      <code class="literal">order</code> property to specify ordering. Remember, the
      higher the order property, the later the view resolver is positioned in
      the chain.</p><p>In the following example, the chain of view resolvers consists of
      two resolvers, an <code class="classname">InternalResourceViewResolver</code>,
      which is always automatically positioned as the last resolver in the
      chain, and an <code class="classname">XmlViewResolver</code> for specifying
      Excel views. Excel views are not supported by the
      <code class="classname">InternalResourceViewResolver</code>.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"jspViewResolver"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.view.InternalResourceViewResolver"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"viewClass"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"org.springframework.web.servlet.view.JstlView"</span>/&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"prefix"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"/WEB-INF/jsp/"</span>/&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"suffix"</span> <span class="hl-attribute">value</span>=<span class="hl-value">".jsp"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"excelViewResolver"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.view.XmlViewResolver"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"order"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"1"</span>/&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"location"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"/WEB-INF/views.xml"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-comment">!-- in views.xml --</span>&gt;

&lt;<span class="hl-tag">beans</span>&gt;
  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">name</span>=<span class="hl-value">"report"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.example.ReportExcelView"</span>/&gt;
&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>If a specific view resolver does not result in a view, Spring
      examines the context for other view resolvers. If additional view
      resolvers exist, Spring continues to inspect them until a view is
      resolved. If no view resolver returns a view, Spring throws a
      <code class="classname">ServletException</code>.</p><p>The contract of a view resolver specifies that a view resolver
      <span class="emphasis"><em>can</em></span> return null to indicate the view could not be
      found. Not all view resolvers do this, however, because in some cases,
      the resolver simply cannot detect whether or not the view exists. For
      example, the <code class="classname">InternalResourceViewResolver</code> uses
      the <code class="classname">RequestDispatcher</code> internally, and dispatching
      is the only way to figure out if a JSP exists, but this action can only
      execute once. The same holds for the
      <code class="classname">VelocityViewResolver</code> and some others. Check the
      Javadoc for the view resolver to see whether it reports non-existing
      views. Thus, putting an
      <code class="classname">InternalResourceViewResolver</code> in the chain in a
      place other than the last, results in the chain not being fully
      inspected, because the
      <code class="classname">InternalResourceViewResolver</code> will
      <span class="emphasis"><em>always</em></span> return a view!</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-redirecting"></a>16.5.3&nbsp;Redirecting to views</h3></div></div></div><p>As mentioned previously, a controller typically returns a logical
      view name, which a view resolver resolves to a particular view
      technology. For view technologies such as JSPs that are processed
      through the Servlet or JSP engine, this resolution is usually handled
      through the combination of
      <code class="classname">InternalResourceViewResolver</code> and
      <code class="classname">InternalResourceView</code>, which issues an internal
      forward or include via the Servlet API's
      <code class="literal">RequestDispatcher.forward(..)</code> method or
      <code class="literal">RequestDispatcher.include()</code> method. For other view
      technologies, such as Velocity, XSLT, and so on, the view itself writes
      the content directly to the response stream.</p><p>It is sometimes desirable to issue an HTTP redirect back to the
      client, before the view is rendered. This is desirable, for example,
      when one controller has been called with <code class="literal">POST</code>ed data,
      and the response is actually a delegation to another controller (for
      example on a successful form submission). In this case, a normal
      internal forward will mean that the other controller will also see the
      same <code class="literal">POST</code> data, which is potentially problematic if
      it can confuse it with other expected data. Another reason to perform a
      redirect before displaying the result is to eliminate the possibility of
      the user submitting the form data multiple times. In this scenario, the
      browser will first send an initial <code class="literal">POST</code>; it will then
      receive a response to redirect to a different URL; and finally the
      browser will perform a subsequent <code class="literal">GET</code> for the URL
      named in the redirect response. Thus, from the perspective of the
      browser, the current page does not reflect the result of a
      <code class="literal">POST</code> but rather of a <code class="literal">GET</code>. The end
      effect is that there is no way the user can accidentally
      re-<code class="literal">POST</code> the same data by performing a refresh. The
      refresh forces a <code class="literal">GET</code> of the result page, not a resend
      of the initial <code class="literal">POST</code> data.</p><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-redirecting-redirect-view"></a>16.5.3.1&nbsp;<code class="classname">RedirectView</code></h4></div></div></div><p>One way to force a redirect as the result of a controller
        response is for the controller to create and return an instance of
        Spring's <code class="classname">RedirectView</code>. In this case,
        <code class="classname">DispatcherServlet</code> does not use the normal view
        resolution mechanism. Rather because it has been given the (redirect)
        view already, the <code class="classname">DispatcherServlet</code> simply
        instructs the view to do its work.</p><p>The <code class="classname">RedirectView</code> issues an
        <code class="literal">HttpServletResponse.sendRedirect()</code> call that
        returns to the client browser as an HTTP redirect.
        All model attributes are considered to be exposed as either URI template variables first, 
        assuming the URL is a URI template such as <code class="code">/account/{number}</code>, 
        or as HTTP query parameters second. By default String and primitive model attributes 
        are eligible to be exposed this way. However, this behavior can be extended by 
        sub-classing RedirectView. Also consider that <code class="code">@PathVariable</code>-annotated 
        method arguments are automatically added to the model, which is convenient when 
        redirecting to the same URL using a different HTTP method. For example:</p><pre class="programlisting">@RequestMapping(value = <span class="hl-string">"/files/{path}"</span>, method = RequestMethod.POST)
<span class="hl-keyword">public</span> String upload(@PathVariable String path, ...) {
    <span class="hl-comment">// ...</span>
    <span class="hl-keyword">return</span> <span class="hl-string">"redirect:files/{path}"</span>;
}

@RequestMapping(value = <span class="hl-string">"/files/{path}"</span>, method = RequestMethod.GET)
<span class="hl-keyword">public</span> <span class="hl-keyword">void</span> get(@PathVariable String path, ...) {
    <span class="hl-comment">// ...</span>
}</pre><p>If you use <code class="classname">RedirectView</code> and the view is
        created by the controller itself, it is recommended that you configure
        the redirect URL to be injected into the controller so that it is not
        baked into the controller but configured in the context along with the
        view names. The next section discusses this process.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-redirecting-redirect-prefix"></a>16.5.3.2&nbsp;The <code class="literal">redirect:</code> prefix</h4></div></div></div><p>While the use of <code class="classname">RedirectView</code> works fine,
        if the controller itself creates the
        <code class="classname">RedirectView</code>, there is no avoiding the fact
        that the controller is aware that a redirection is happening. This is
        really suboptimal and couples things too tightly. The controller
        should not really care about how the response gets handled. In general
        it should operate only in terms of view names that have been injected
        into it.</p><p>The special <code class="literal">redirect:</code> prefix allows you to
        accomplish this. If a view name is returned that has the prefix
        <code class="literal">redirect:</code>, the
        <code class="classname">UrlBasedViewResolver</code> (and all subclasses) will
        recognize this as a special indication that a redirect is needed. The
        rest of the view name will be treated as the redirect URL.</p><p>The net effect is the same as if the controller had returned a
        <code class="classname">RedirectView</code>, but now the controller itself can
        simply operate in terms of logical view names. A logical view name
        such as <code class="literal">redirect:/myapp/some/resource</code> will
        redirect relative to the current servlet context, while a name such as
        <code class="literal">redirect:http://myhost.com/some/arbitrary/path</code>
        will redirect to an absolute URL.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="mvc-redirecting-forward-prefix"></a>16.5.3.3&nbsp;The <code class="literal">forward:</code> prefix</h4></div></div></div><p>It is also possible to use a special <code class="literal">forward:</code>
        prefix for view names that are ultimately resolved by
        <code class="classname">UrlBasedViewResolver</code> and subclasses. This
        creates an <code class="classname">InternalResourceView</code> (which
        ultimately does a <code class="literal">RequestDispatcher.forward()</code>)
        around the rest of the view name, which is considered a URL.
        Therefore, this prefix is not useful with
        <code class="classname">InternalResourceViewResolver</code> and
        <code class="classname">InternalResourceView</code> (for JSPs for example).
        But the prefix can be helpful when you are primarily using another
        view technology, but still want to force a forward of a resource to be
        handled by the Servlet/JSP engine. (Note that you may also chain
        multiple view resolvers, instead.)</p><p>As with the <code class="literal">redirect:</code> prefix, if the view
        name with the <code class="literal">forward:</code> prefix is injected into the
        controller, the controller does not detect that anything special is
        happening in terms of handling the response.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-multiple-representations"></a>16.5.4&nbsp;<code class="classname">ContentNegotiatingViewResolver</code></h3></div></div></div><p>The <code class="classname">ContentNegotiatingViewResolver</code> does not
      resolve views itself but rather delegates to other view resolvers,
      selecting the view that resembles the representation requested by the
      client. Two strategies exist for a client to request a representation
      from the server:</p><div class="itemizedlist"><ul type="disc"><li><p>Use a distinct URI for each resource, typically by using a
          different file extension in the URI. For example, the URI<code class="literal">
          http://www.example.com/users/fred.pdf</code> requests a PDF
          representation of the user fred, and
          <code class="literal">http://www.example.com/users/fred.xml</code> requests an
          XML representation.</p></li></ul></div><div class="itemizedlist"><ul type="disc"><li><p>Use the same URI for the client to locate the resource, but
          set the <code class="literal">Accept</code> HTTP request header to list the
          <a class="ulink" href="http://en.wikipedia.org/wiki/Internet_media_type" target="_top">media
          types</a> that it understands. For example, an HTTP request for
          <code class="literal">http://www.example.com/users/fred</code> with an
          <code class="literal">Accept</code> header set to <code class="literal">application/pdf
          </code>requests a PDF representation of the user fred, while
          <code class="literal">http://www.example.com/users/fred</code> with an
          <code class="literal">Accept</code> header set to <code class="literal">text/xml</code>
          requests an XML representation. This strategy is known as <a class="ulink" href="http://en.wikipedia.org/wiki/Content_negotiation" target="_top">content
          negotiation</a>.</p></li></ul></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>One issue with the <code class="literal">Accept</code> header is that it
        is impossible to set it in a web browser within HTML. For example, in
        Firefox, it is fixed to:</p><pre class="programlisting">Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8</pre><p>For this reason it is common to see the use of a distinct URI
        for each representation when developing browser based web
        applications.</p></td></tr></table></div><p>To support multiple representations of a resource, Spring provides
      the <code class="classname">ContentNegotiatingViewResolver</code> to resolve a
      view based on the file extension or <code class="literal">Accept</code> header of
      the HTTP request. <code class="classname">ContentNegotiatingViewResolver</code>
      does not perform the view resolution itself but instead delegates to a
      list of view resolvers that you specify through the bean property
      <code class="literal">ViewResolvers</code>.</p><p>The <code class="classname">ContentNegotiatingViewResolver</code> selects
      an appropriate <code class="classname">View</code> to handle the request by
      comparing the request media type(s) with the media type (also known as
      <code class="literal">Content-Type</code>) supported by the
      <code class="classname">View</code> associated with each of its
      <code class="classname">ViewResolvers</code>. The first
      <code class="classname">View</code> in the list that has a compatible
      <code class="literal">Content-Type</code> returns the representation to the
      client. If a compatible view cannot be supplied by the
      <code class="classname">ViewResolver</code> chain, then the list of views
      specified through the <code class="literal">DefaultViews</code> property will be
      consulted. This latter option is appropriate for singleton
      <code class="classname">Views</code> that can render an appropriate
      representation of the current resource regardless of the logical view
      name. The <code class="literal">Accept</code> header may include wildcards, for
      example text/*, in which case a <code class="classname">View</code> whose
      Content-Type was text/xml is a compatible match.</p><p>To support the resolution of a view based on a file extension, use
      the <code class="classname">ContentNegotiatingViewResolver </code>bean property
      <code class="literal">mediaTypes</code> to specify a mapping of file extensions to
      media types. For more information on the algorithm used to determine the
      request media type, refer to the API documentation for
      <code class="classname">ContentNegotiatingViewResolver</code>.</p><p>Here is an example configuration of a
      <code class="classname">ContentNegotiatingViewResolver:</code></p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.view.ContentNegotiatingViewResolver"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"mediaTypes"</span>&gt;
    &lt;<span class="hl-tag">map</span>&gt;
      &lt;<span class="hl-tag">entry</span> <span class="hl-attribute">key</span>=<span class="hl-value">"atom"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"application/atom+xml"</span>/&gt;
      &lt;<span class="hl-tag">entry</span> <span class="hl-attribute">key</span>=<span class="hl-value">"html"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"text/html"</span>/&gt;
      &lt;<span class="hl-tag">entry</span> <span class="hl-attribute">key</span>=<span class="hl-value">"json"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"application/json"</span>/&gt;
    &lt;<span class="hl-tag">/map</span>&gt;
  &lt;<span class="hl-tag">/property</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"viewResolvers"</span>&gt;
    &lt;<span class="hl-tag">list</span>&gt;
      &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.view.BeanNameViewResolver"</span>/&gt;
      &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.view.InternalResourceViewResolver"</span>&gt;
        &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"prefix"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"/WEB-INF/jsp/"</span>/&gt;
        &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"suffix"</span> <span class="hl-attribute">value</span>=<span class="hl-value">".jsp"</span>/&gt;
      &lt;<span class="hl-tag">/bean</span>&gt;
    &lt;<span class="hl-tag">/list</span>&gt;
  &lt;<span class="hl-tag">/property</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"defaultViews"</span>&gt;
    &lt;<span class="hl-tag">list</span>&gt;
      &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.view.json.MappingJacksonJsonView"</span> /&gt;
    &lt;<span class="hl-tag">/list</span>&gt;
  &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;


&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"content"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.springsource.samples.rest.SampleContentAtomView"</span>/&gt;</pre><p>The <code class="classname">InternalResourceViewResolver</code> handles
      the translation of view names and JSP pages, while the
      <code class="classname">BeanNameViewResolver</code> returns a view based on the
      name of a bean. (See "<a class="link" href="mvc.html#mvc-viewresolver-resolver" title="16.5.1&nbsp;Resolving views with the ViewResolver interface">Resolving views with the
      ViewResolver interface</a>" for more details on how Spring looks up
      and instantiates a view.) In this example, the
      <code class="literal">content</code> bean is a class that inherits from
      <code class="classname">AbstractAtomFeedView</code>, which returns an Atom RSS
      feed. For more information on creating an Atom Feed representation, see
      the section Atom Views.</p><p>In the above configuration, if a request is made with an
      <code class="literal">.html</code> extension, the view resolver looks for a view
      that matches the <code class="literal">text/html</code> media type. The
      <code class="classname">InternalResourceViewResolver</code> provides the
      matching view for <code class="literal">text/html</code>. If the request is made
      with the file extension <code class="literal">.atom</code>, the view resolver
      looks for a view that matches the
      <code class="literal">application/atom+xml</code> media type. This view is
      provided by the <code class="classname">BeanNameViewResolver</code> that maps to
      the <code class="classname">SampleContentAtomView</code> if the view name
      returned is <code class="classname">content</code>. If the request is made with
      the file extension <code class="literal">.json</code>, the
      <code class="classname">MappingJacksonJsonView</code> instance from the
      <code class="literal">DefaultViews</code> list will be selected regardless of the
      view name. Alternatively, client requests can be made without a file
      extension but with the <code class="literal">Accept</code> header set to the
      preferred media-type, and the same resolution of request to views would
      occur.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>If <code class="classname">ContentNegotiatingViewResolver</code>'s list
        of ViewResolvers is not configured explicitly, it automatically uses
        any ViewResolvers defined in the application context.</p></td></tr></table></div><p>The corresponding controller code that returns an Atom RSS feed
      for a URI of the form <code class="literal">http://localhost/content.atom</code>
      or <code class="literal">http://localhost/content</code> with an
      <code class="literal">Accept</code> header of application/atom+xml is shown
      below.</p><pre class="programlisting">@Controller
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ContentController {

    <span class="hl-keyword">private</span> List&lt;SampleContent&gt; contentList = <span class="hl-keyword">new</span> ArrayList&lt;SampleContent&gt;();

    @RequestMapping(value=<span class="hl-string">"/content"</span>, method=RequestMethod.GET)
    <span class="hl-keyword">public</span> ModelAndView getContent() {
        ModelAndView mav = <span class="hl-keyword">new</span> ModelAndView();
        mav.setViewName(<span class="hl-string">"content"</span>);
        mav.addObject(<span class="hl-string">"sampleContentList"</span>, contentList);
        <span class="hl-keyword">return</span> mav;
    }

}</pre></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="mvc-localeresolver"></a>16.6&nbsp;Using locales</h2></div></div></div><p>Most parts of Spring's architecture support internationalization,
    just as the Spring web MVC framework does.
    <code class="classname">DispatcherServlet</code> enables you to automatically
    resolve messages using the client's locale. This is done with
    <code class="interfacename">LocaleResolver</code> objects.</p><p>When a request comes in, the
    <code class="classname">DispatcherServlet</code> looks for a locale resolver, and
    if it finds one it tries to use it to set the locale. Using the
    <code class="literal">RequestContext.getLocale()</code> method, you can always
    retrieve the locale that was resolved by the locale resolver.</p><p>In addition to automatic locale resolution, you can also attach an
    interceptor to the handler mapping (see <a class="xref" href="mvc.html#mvc-handlermapping-interceptor" title="16.4.1&nbsp;Intercepting requests with a HandlerInterceptor">Section&nbsp;16.4.1, &#8220;Intercepting requests with a
      HandlerInterceptor&#8221;</a> for more information on
    handler mapping interceptors) to change the locale under specific
    circumstances, for example, based on a parameter in the request.</p><p>Locale resolvers and interceptors are defined in the
    <code class="literal">org.springframework.web.servlet.i18n</code> package and are
    configured in your application context in the normal way. Here is a
    selection of the locale resolvers included in Spring.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-localeresolver-acceptheader"></a>16.6.1&nbsp;<code class="classname">AcceptHeaderLocaleResolver</code></h3></div></div></div><p>This locale resolver inspects the
      <code class="literal">accept-language</code> header in the request that was sent
      by the client (e.g., a web browser). Usually this header field contains
      the locale of the client's operating system.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-localeresolver-cookie"></a>16.6.2&nbsp;<code class="classname">CookieLocaleResolver</code></h3></div></div></div><p>This locale resolver inspects a <code class="classname">Cookie</code> that
      might exist on the client to see if a locale is specified. If so, it
      uses the specified locale. Using the properties of this locale resolver,
      you can specify the name of the cookie as well as the maximum age. Find
      below an example of defining a
      <code class="classname">CookieLocaleResolver</code>.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"localeResolver"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.i18n.CookieLocaleResolver"</span>&gt;

    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"cookieName"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"clientlanguage"</span>/&gt;
    
    &lt;<span class="hl-comment">!-- in seconds. If set to -1, the cookie is not persisted (deleted when browser shuts down) --</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"cookieMaxAge"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"100000"</span>&gt;

&lt;<span class="hl-tag">/bean</span>&gt;</pre><div class="table"><a name="mvc-cookie-locale-resolver-props-tbl"></a><p class="title"><b>Table&nbsp;16.4.&nbsp;<code class="classname">CookieLocaleResolver</code> properties</b></p><div class="table-contents"><table summary="CookieLocaleResolver properties" style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Property</th><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Default</th><th style="border-bottom: 1.0pt solid ; ">Description</th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">cookieName</td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">classname + LOCALE</td><td style="border-bottom: 1.0pt solid ; ">The name of the cookie</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">cookieMaxAge</td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Integer.MAX_INT</td><td style="border-bottom: 1.0pt solid ; ">The maximum time a cookie will stay persistent on the
              client. If -1 is specified, the cookie will not be persisted; it
              will only be available until the client shuts down his or her
              browser.</td></tr><tr><td style="border-right: 1.0pt solid ; ">cookiePath</td><td style="border-right: 1.0pt solid ; ">/</td><td style="">Limits the visibility of the cookie to a certain part of
              your site. When cookiePath is specified, the cookie will only be
              visible to that path and the paths below it.</td></tr></tbody></table></div></div><br class="table-break"></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-localeresolver-session"></a>16.6.3&nbsp;<code class="classname">SessionLocaleResolver</code></h3></div></div></div><p>The <code class="classname">SessionLocaleResolver</code> allows you to
      retrieve locales from the session that might be associated with the
      user's request.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-localeresolver-interceptor"></a>16.6.4&nbsp;<code class="classname">LocaleChangeInterceptor</code></h3></div></div></div><p>You can enable changing of locales by adding the
      <code class="classname">LocaleChangeInterceptor</code> to one of the handler
      mappings (see <a class="xref" href="mvc.html#mvc-handlermapping" title="16.4&nbsp;Handler mappings">Section&nbsp;16.4, &#8220;Handler mappings&#8221;</a>). It will detect a
      parameter in the request and change the locale. It calls
      <code class="literal">setLocale()</code> on the
      <code class="interfacename">LocaleResolver</code> that also exists in the
      context. The following example shows that calls to all
      <code class="literal">*.view</code> resources containing a parameter named
      <code class="literal">siteLanguage</code> will now change the locale. So, for
      example, a request for the following URL,
      <code class="literal">http://www.sf.net/home.view?siteLanguage=nl</code> will
      change the site language to Dutch.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"localeChangeInterceptor"</span>
      <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.i18n.LocaleChangeInterceptor"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"paramName"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"siteLanguage"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"localeResolver"</span>
      <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.i18n.CookieLocaleResolver"</span>/&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"urlMapping"</span>
      <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"interceptors"</span>&gt;
        &lt;<span class="hl-tag">list</span>&gt;
            &lt;<span class="hl-tag">ref</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"localeChangeInterceptor"</span>/&gt;
        &lt;<span class="hl-tag">/list</span>&gt;
    &lt;<span class="hl-tag">/property</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"mappings"</span>&gt;
        &lt;<span class="hl-tag">value</span>&gt;/**/*.view=someController&lt;<span class="hl-tag">/value</span>&gt;
    &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="mvc-themeresolver"></a>16.7&nbsp;Using themes</h2></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-themeresolver-introduction"></a>16.7.1&nbsp;Overview of themes</h3></div></div></div><p>You can apply Spring Web MVC framework themes to set the overall
      look-and-feel of your application, thereby enhancing user experience. A
      theme is a collection of static resources, typically style sheets and
      images, that affect the visual style of the application.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-themeresolver-defining"></a>16.7.2&nbsp;Defining themes</h3></div></div></div><p>To use themes in your web application, you must set up an
      implementation of the
      <code class="interfacename">org.springframework.ui.context.ThemeSource</code>
      interface. The <code class="interfacename">WebApplicationContext</code>
      interface extends <code class="interfacename">ThemeSource</code> but
      delegates its responsibilities to a dedicated implementation. By default
      the delegate will be an
      <code class="classname">org.springframework.ui.context.support.ResourceBundleThemeSource</code>
      implementation that loads properties files from the root of the
      classpath. To use a custom <code class="interfacename">ThemeSource</code>
      implementation or to configure the base name prefix of the
      <code class="classname">ResourceBundleThemeSource</code>, you can register a
      bean in the application context with the reserved name
      <code class="classname">themeSource</code>. The web application context
      automatically detects a bean with that name and uses it.</p><p>When using the <code class="classname">ResourceBundleThemeSource</code>, a
      theme is defined in a simple properties file. The
      properties file lists the resources that make up the theme. Here is an
      example:</p><pre class="programlisting">styleSheet=/themes/cool/style.css
background=/themes/cool/img/coolBg.jpg</pre><p>The keys of the properties are the names that refer to the themed
      elements from view code. For a JSP, you typically do this using the
      <code class="literal">spring:theme</code> custom tag, which is very similar to the
      <code class="literal">spring:message</code> tag. The following JSP fragment uses
      the theme defined in the previous example to customize the look and
      feel:</p><pre class="programlisting">&lt;<span class="hl-tag">%@</span> <span class="hl-attribute">taglib</span> <span class="hl-attribute">prefix</span>=<span class="hl-value">"spring"</span> <span class="hl-attribute">uri</span>=<span class="hl-value">"http://www.springframework.org/tags"</span><span class="hl-attribute">%&gt;</span>
<span class="hl-attribute">&lt;html&gt;</span>
   <span class="hl-attribute">&lt;head&gt;</span>
      <span class="hl-attribute">&lt;link</span> <span class="hl-attribute">rel</span>=<span class="hl-value">"stylesheet"</span> <span class="hl-attribute">href</span>=<span class="hl-value">"&lt;spring:theme code='styleSheet'/&gt;"</span> <span class="hl-attribute">type</span>=<span class="hl-value">"text/css"</span>/&gt;
   &lt;<span class="hl-tag">/head</span>&gt;
   &lt;<span class="hl-tag">body</span> <span class="hl-attribute">style</span>=<span class="hl-value">"background=&lt;spring:theme code='background'/&gt;"</span>&gt;
      ...
   &lt;<span class="hl-tag">/body</span>&gt;
&lt;<span class="hl-tag">/html</span>&gt;</pre><p>By default, the <code class="classname">ResourceBundleThemeSource</code>
      uses an empty base name prefix. As a result, the properties files are
      loaded from the root of the classpath. Thus you would put the
      <code class="literal">cool.properties</code> theme definition in a directory at
      the root of the classpath, for example, in
      <code class="literal">/WEB-INF/classes</code>. The
      <code class="classname">ResourceBundleThemeSource</code> uses the standard Java
      resource bundle loading mechanism, allowing for full
      internationalization of themes. For example, we could have a
      <code class="literal">/WEB-INF/classes/cool_nl.properties</code> that references a
      special background image with Dutch text on it.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-themeresolver-resolving"></a>16.7.3&nbsp;Theme resolvers</h3></div></div></div><p>After you define themes, as in the preceding section, you decide
      which theme to use. The <code class="classname">DispatcherServlet</code> will
      look for a bean named <code class="classname">themeResolver</code> to find out
      which <code class="interfacename">ThemeResolver</code> implementation to
      use. A theme resolver works in much the same way as a
      <code class="interfacename">LocaleResolver</code>. It detects the theme to
      use for a particular request and can also alter the request's theme. The
      following theme resolvers are provided by Spring:</p><div class="table"><a name="mvc-theme-resolver-impls-tbl"></a><p class="title"><b>Table&nbsp;16.5.&nbsp;<code class="interfacename">ThemeResolver</code>
        implementations</b></p><div class="table-contents"><table summary="ThemeResolver&#xA;        implementations" style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Class</th><th style="border-bottom: 1.0pt solid ; ">Description</th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">FixedThemeResolver</code></td><td style="border-bottom: 1.0pt solid ; ">Selects a fixed theme, set using the
              <code class="classname">defaultThemeName</code> property.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">SessionThemeResolver</code></td><td style="border-bottom: 1.0pt solid ; ">The theme is maintained in the user's HTTP session. It
              only needs to be set once for each session, but is not persisted
              between sessions.</td></tr><tr><td style="border-right: 1.0pt solid ; "><code class="classname">CookieThemeResolver</code></td><td style="">The selected theme is stored in a cookie on the
              client.</td></tr></tbody></table></div></div><br class="table-break"><p>Spring also provides a
      <code class="classname">ThemeChangeInterceptor</code> that allows theme changes
      on every request with a simple request parameter.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="mvc-multipart"></a>16.8&nbsp;Spring's multipart (fileupload) support</h2></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-multipart-introduction"></a>16.8.1&nbsp;Introduction</h3></div></div></div><p>Spring's built-in multipart support handles file uploads in web
      applications. You enable this multipart support with pluggable
      <code class="interfacename">MultipartResolver</code> objects, defined in the
      <code class="literal">org.springframework.web.multipart</code> package. Spring
      provides a <code class="interfacename">MultipartResolver</code> for use with
      <a class="ulink" href="http://jakarta.apache.org/commons/fileupload" target="_top">
      <span class="emphasis"><em>Commons FileUpload</em></span></a>).</p><p>By default, Spring does no multipart handling, because some
      developers want to handle multiparts themselves. You enable Spring
      multipart handling by adding a multipart resolver to the web
      application's context. Each request is inspected to see if it contains a
      multipart. If no multipart is found, the request continues as expected.
      If a multipart is found in the request, the
      <code class="classname">MultipartResolver</code> that has been declared in your
      context is used. After that, the multipart attribute in your request is
      treated like any other attribute.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-multipart-resolver"></a>16.8.2&nbsp;Using the
      <code class="interfacename">MultipartResolver</code></h3></div></div></div><p>The following example shows how to use the
      <code class="classname">CommonsMultipartResolver</code>:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"multipartResolver"</span>
    <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.multipart.commons.CommonsMultipartResolver"</span>&gt;

    &lt;<span class="hl-comment">!-- one of the properties available; the maximum file size in bytes --</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"maxUploadSize"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"100000"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>Of course you also need to put the appropriate jars in your
      classpath for the multipart resolver to work. In the case of the
      <code class="classname">CommonsMultipartResolver</code>, you need to use
      <code class="literal">commons-fileupload.jar</code>.</p><p>When the Spring <code class="classname">DispatcherServlet</code> detects a
      multi-part request, it activates the resolver that has been declared in
      your context and hands over the request. The resolver then wraps the
      current <code class="classname">HttpServletRequest</code> into a
      <code class="classname">MultipartHttpServletRequest</code> that supports
      multipart file uploads. Using the
      <code class="classname">MultipartHttpServletRequest</code>, you can get
      information about the multiparts contained by this request and actually
      get access to the multipart files themselves in your controllers.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-multipart-forms"></a>16.8.3&nbsp;Handling a file upload in a form</h3></div></div></div><p>After the <code class="classname">MultipartResolver</code> completes its
      job, the request is processed like any other. First, create a form with
      a file input that will allow the user to upload a form. The encoding
      attribute (<code class="literal">enctype="multipart/form-data"</code>) lets the
      browser know how to encode the form as multipart request:</p><pre class="programlisting">&lt;<span class="hl-tag">html</span>&gt;
    &lt;<span class="hl-tag">head</span>&gt;
        &lt;<span class="hl-tag">title</span>&gt;Upload a file please&lt;<span class="hl-tag">/title</span>&gt;
    &lt;<span class="hl-tag">/head</span>&gt;
    &lt;<span class="hl-tag">body</span>&gt;
        &lt;<span class="hl-tag">h1</span>&gt;Please upload a file&lt;<span class="hl-tag">/h1</span>&gt;
        &lt;<span class="hl-tag">form</span> <span class="hl-attribute">method</span>=<span class="hl-value">"post"</span> <span class="hl-attribute">action</span>=<span class="hl-value">"/form"</span> <span class="hl-attribute">enctype</span>=<span class="hl-value">"multipart/form-data"</span>&gt;
            &lt;<span class="hl-tag">input</span> <span class="hl-attribute">type</span>=<span class="hl-value">"text"</span> <span class="hl-attribute">name</span>=<span class="hl-value">"name"</span>/&gt;
            &lt;<span class="hl-tag">input</span> <span class="hl-attribute">type</span>=<span class="hl-value">"file"</span> <span class="hl-attribute">name</span>=<span class="hl-value">"file"</span>/&gt;
            &lt;<span class="hl-tag">input</span> <span class="hl-attribute">type</span>=<span class="hl-value">"submit"</span>/&gt;
        &lt;<span class="hl-tag">/form</span>&gt;
    &lt;<span class="hl-tag">/body</span>&gt;
&lt;<span class="hl-tag">/html</span>&gt;</pre><p>The next step is to create a controller that handles the file
      upload. This controller is very similar to a <a class="link" href="mvc.html#mvc-ann-controller" title="16.3.1&nbsp;Defining a controller with @Controller">normal annotated
      <code class="interfacename">@Controller</code></a>, except that we use
      <code class="classname">MultipartHttpServletRequest</code> or
      <code class="filename">MultipartFile</code> in the method parameters:
      </p><pre class="programlisting">@Controller
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> FileUpoadController {

    @RequestMapping(value = <span class="hl-string">"/form"</span>, method = RequestMethod.POST)
    <span class="hl-keyword">public</span> String handleFormUpload(@RequestParam(<span class="hl-string">"name"</span>) String name,
        @RequestParam(<span class="hl-string">"file"</span>) MultipartFile file) {

        <span class="hl-keyword">if</span> (!file.isEmpty()) {
            <span class="hl-keyword">byte</span>[] bytes = file.getBytes();
            <span class="hl-comment">// store the bytes somewhere</span>
           <span class="hl-keyword">return</span> <span class="hl-string">"redirect:uploadSuccess"</span>;
       } <span class="hl-keyword">else</span> {
           <span class="hl-keyword">return</span> <span class="hl-string">"redirect:uploadFailure"</span>;
       }
    }

}</pre><p>Note how the <code class="interfacename">@RequestParam</code> method
      parameters map to the input elements declared in the form. In this
      example, nothing is done with the <code class="literal">byte[]</code>, but in
      practice you can save it in a database, store it on the file system, and
      so on.</p><p>Finally, you will have to declare the controller and the resolver
      in the application context:</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;
    &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"multipartResolver"</span>
        <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.multipart.commons.CommonsMultipartResolver"</span>/&gt;
    &lt;<span class="hl-comment">!-- Declare explicitly, or use &lt;context:annotation-config/&gt; --</span>&gt;
    &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"fileUploadController"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.FileUploadController"</span>/&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="mvc-exceptionhandlers"></a>16.9&nbsp;Handling exceptions</h2></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d0e30561"></a>16.9.1&nbsp;<code class="interfacename">HandlerExceptionResolver</code></h3></div></div></div><p>Spring <code class="literal">HandlerExceptionResolver</code> implementations deal
      with unexpected exceptions that occur during controller execution.
      A <code class="literal">HandlerExceptionResolver</code> somewhat resembles the
      exception mappings you can define in the web application descriptor
      <code class="literal">web.xml</code>. However, they provide a more flexible way to
      do so. For example they provide information about which handler was
      executing when the exception was thrown. Furthermore, a programmatic way
      of handling exceptions gives you more options for responding
      appropriately before the request is forwarded to another URL (the same
      end result as when you use the servlet specific exception
      mappings).</p><p>Besides implementing the
      <code class="interfacename">HandlerExceptionResolver</code> interface, which
      is only a matter of implementing the
      <code class="literal">resolveException(Exception, Handler)</code> method and
      returning a <code class="classname">ModelAndView</code>, you may also use the
      <code class="classname">SimpleMappingExceptionResolver</code>. This resolver
      enables you to take the class name of any exception that might be thrown
      and map it to a view name. This is functionally equivalent to the
      exception mapping feature from the Servlet API, but it is also possible
      to implement more finely grained mappings of exceptions from different
      handlers.</p><p>By default, the <code class="classname">DispatcherServlet</code> registers
      the <code class="classname">DefaultHandlerExceptionResolver</code>. This resolver
      handles certain standard Spring MVC exceptions by setting a specific
      response status code:
      </p><div class="informaltable"><table style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Exception</th><th style="border-bottom: 1.0pt solid ; ">HTTP Status Code</th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">ConversionNotSupportedException</code></td><td style="border-bottom: 1.0pt solid ; ">500 (Internal Server Error)</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">HttpMediaTypeNotAcceptableException</code></td><td style="border-bottom: 1.0pt solid ; ">406 (Not Acceptable)</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">HttpMediaTypeNotSupportedException</code></td><td style="border-bottom: 1.0pt solid ; ">415 (Unsupported Media Type)</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">HttpMessageNotReadableException</code></td><td style="border-bottom: 1.0pt solid ; ">400 (Bad Request)</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">HttpMessageNotWritableException</code></td><td style="border-bottom: 1.0pt solid ; ">500 (Internal Server Error)</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">HttpRequestMethodNotSupportedException</code></td><td style="border-bottom: 1.0pt solid ; ">405 (Method Not Allowed)</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">MissingServletRequestParameterException</code></td><td style="border-bottom: 1.0pt solid ; ">400 (Bad Request)</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">NoSuchRequestHandlingMethodException</code></td><td style="border-bottom: 1.0pt solid ; ">404 (Not Found)</td></tr><tr><td style="border-right: 1.0pt solid ; "><code class="classname">TypeMismatchException</code></td><td style="">400 (Bad Request)</td></tr></tbody></table></div><p>
      </p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-ann-exceptionhandler"></a>16.9.2&nbsp;<code class="interfacename">@ExceptionHandler</code></h3></div></div></div><p>An alternative to the
      <code class="interfacename">HandlerExceptionResolver</code> interface is the
      <code class="interfacename">@ExceptionHandler</code> annotation. You use the
      <code class="classname">@ExceptionHandler</code> method annotation within a
      controller to specify which method is invoked when an exception of a
      specific type is thrown during the execution of controller methods. For
      example:</p><pre class="programlisting">@Controller
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleController {

  <span class="hl-comment">// other controller method omitted</span>

  @ExceptionHandler(IOException.<span class="hl-keyword">class</span>)
  <span class="hl-keyword">public</span> String handleIOException(IOException ex, HttpServletRequest request) {
    <span class="hl-keyword">return</span> ClassUtils.getShortName(ex.getClass());
  }
}</pre><p>will invoke the 'handlerIOException' method when a
      <code class="classname">java.io.IOException</code> is thrown.</p><p>The <code class="classname">@ExceptionHandler</code> value can be set to
      an array of Exception types. If an exception is thrown matches one of
      the types in the list, then the method annotated with the matching
      <code class="classname">@ExceptionHandler</code> will be invoked. If the
      annotation value is not set then the exception types listed as method
      arguments are used.</p><p>Much like standard controller methods annotated with a
      <code class="classname">@RequestMapping</code> annotation, the method arguments
      and return values of <code class="classname">@ExceptionHandler</code> methods
      are very flexible. For example, the
      <code class="classname">HttpServletRequest</code> can be accessed in Servlet
      environments and the <code class="classname">PortletRequest</code> in Portlet
      environments. The return type can be a <code class="classname">String</code>,
      which is interpreted as a view name or a
      <code class="classname">ModelAndView</code> object. Refer to the API
      documentation for more details.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="mvc-coc"></a>16.10&nbsp;Convention over configuration support</h2></div></div></div><p>For a lot of projects, sticking to established conventions and
    having reasonable defaults is just what they (the projects) need... this
    theme of convention-over-configuration now has explicit support in Spring
    Web MVC. What this means is that if you establish a set of naming
    conventions and suchlike, you can <span class="emphasis"><em>substantially</em></span> cut
    down on the amount of configuration that is required to set up handler
    mappings, view resolvers, <code class="classname">ModelAndView</code> instances,
    etc. This is a great boon with regards to rapid prototyping, and can also
    lend a degree of (always good-to-have) consistency across a codebase
    should you choose to move forward with it into production.</p><p>Convention-over-configuration support addresses the three core areas
    of MVC -- models, views, and controllers.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-coc-ccnhm"></a>16.10.1&nbsp;The Controller
      <code class="classname">ControllerClassNameHandlerMapping</code></h3></div></div></div><p>The <code class="classname">ControllerClassNameHandlerMapping</code> class
      is a <code class="interfacename">HandlerMapping</code> implementation that
      uses a convention to determine the mapping between request URLs and the
      <code class="interfacename">Controller</code> instances that are to handle
      those requests.</p><p>Consider the following simple
      <code class="interfacename">Controller</code> implementation. Take special
      notice of the <span class="emphasis"><em>name</em></span> of the class.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ViewShoppingCartController <span class="hl-keyword">implements</span> Controller {

    <span class="hl-keyword">public</span> ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
        <span class="hl-comment">// the implementation is not hugely important for this example...</span>
    }
}</pre><p>Here is a snippet from the attendent Spring Web MVC configuration
      file...</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"</span>/&gt;
                
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"viewShoppingCart"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"x.y.z.ViewShoppingCartController"</span>&gt;
    &lt;<span class="hl-comment">!-- inject dependencies as required... --</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The <code class="classname">ControllerClassNameHandlerMapping</code> finds
      all of the various handler (or
      <code class="interfacename">Controller</code>) beans defined in its
      application context and strips <code class="literal">Controller</code> off the
      name to define its handler mappings. Thus,
      <code class="classname">ViewShoppingCartController</code> maps to the
      <code class="literal">/viewshoppingcart*</code> request URL.</p><p>Let's look at some more examples so that the central idea becomes
      immediately familiar. (Notice all lowercase in the URLs, in contrast to
      camel-cased <code class="interfacename">Controller</code> class
      names.)</p><div class="itemizedlist"><ul type="disc"><li><p><code class="classname">WelcomeController</code> maps to the
          <code class="literal">/welcome*</code> request URL</p></li><li><p><code class="classname">HomeController</code> maps to the
          <code class="literal">/home*</code> request URL</p></li><li><p><code class="classname">IndexController</code> maps to the
          <code class="literal">/index*</code> request URL</p></li><li><p><code class="classname">RegisterController</code> maps to the
          <code class="literal">/register*</code> request URL</p></li></ul></div><p>In the case of <code class="classname">MultiActionController</code>
      handler classes, the mappings generated are slightly more complex. The
      <code class="interfacename">Controller</code> names in the following
      examples are assumed to be <code class="classname">MultiActionController</code>
      implementations:</p><div class="itemizedlist"><ul type="disc"><li><p><code class="classname">AdminController</code> maps to the
          <code class="literal">/admin</code><span class="bold"><strong>/*</strong></span> request
          URL</p></li><li><p><code class="classname">CatalogController</code> maps to the
          <code class="literal">/catalog</code><span class="bold"><strong>/*</strong></span>
          request URL</p></li></ul></div><p>If you follow the convention of naming your
      <code class="interfacename">Controller</code> implementations as
      <code class="literal">xxx</code><span class="bold"><strong>Controller</strong></span>, the
      <code class="classname">ControllerClassNameHandlerMapping</code> saves you the
      tedium of defining and maintaining a potentially
      <span class="emphasis"><em>looooong</em></span>
      <code class="classname">SimpleUrlHandlerMapping</code> (or suchlike).</p><p>The <code class="classname">ControllerClassNameHandlerMapping</code> class
      extends the <code class="classname">AbstractHandlerMapping</code> base class so
      you can define <code class="interfacename">HandlerInterceptor</code>
      instances and everything else just as you would with many other
      <code class="interfacename">HandlerMapping</code> implementations.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-coc-modelmap"></a>16.10.2&nbsp;The Model <code class="classname">ModelMap</code>
      (<code class="classname">ModelAndView</code>)</h3></div></div></div><p>The <code class="classname">ModelMap</code> class is essentially a
      glorified <code class="interfacename">Map</code> that can make adding
      objects that are to be displayed in (or on) a
      <code class="interfacename">View</code> adhere to a common naming
      convention. Consider the following
      <code class="interfacename">Controller</code> implementation; notice that
      objects are added to the <code class="classname">ModelAndView</code> without any
      associated name specified.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> DisplayShoppingCartController <span class="hl-keyword">implements</span> Controller {

    <span class="hl-keyword">public</span> ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
        
        List cartItems = <span class="hl-comment">// get a List of CartItem objects</span>
        User user = <span class="hl-comment">// get the User doing the shopping</span>
        
        ModelAndView mav = <span class="hl-keyword">new</span> ModelAndView(<span class="hl-string">"displayShoppingCart"</span>); &lt;-- the logical view name

        mav.addObject(cartItems); &lt;-- look ma, no name, just the object
        mav.addObject(user); &lt;-- and again ma!

        <span class="hl-keyword">return</span> mav;
    }
}</pre><p>The <code class="classname">ModelAndView</code> class uses a
      <code class="classname">ModelMap</code> class that is a custom
      <code class="interfacename">Map</code> implementation that automatically
      generates a key for an object when an object is added to it. The
      strategy for determining the name for an added object is, in the case of
      a scalar object such as <code class="classname">User</code>, to use the short
      class name of the object's class. The following examples are names that
      are generated for scalar objects put into a
      <code class="classname">ModelMap</code> instance.</p><div class="itemizedlist"><ul type="disc"><li><p>An <code class="classname">x.y.User</code> instance added will have
          the name <code class="literal">user</code> generated.</p></li><li><p>An <code class="classname">x.y.Registration</code> instance added will
          have the name <code class="literal">registration</code> generated.</p></li><li><p>An <code class="classname">x.y.Foo</code> instance added will have the
          name <code class="literal">foo</code> generated.</p></li><li><p>A <code class="classname">java.util.HashMap</code> instance added will
          have the name <code class="literal">hashMap</code> generated. You probably
          want to be explicit about the name in this case because
          <code class="literal">hashMap</code> is less than intuitive.</p></li><li><p>Adding <code class="literal">null</code> will result in an
          <code class="classname">IllegalArgumentException</code> being thrown. If the
          object (or objects) that you are adding could be
          <code class="literal">null</code>, then you will also want to be explicit
          about the name.</p></li></ul></div><div class="sidebar"><p class="title"><b>What, no automatic pluralization?</b></p><p>Spring Web MVC's convention-over-configuration support does not
        support automatic pluralization. That is, you cannot add a
        <code class="interfacename">List</code> of <code class="classname">Person</code>
        objects to a <code class="classname">ModelAndView</code> and have the
        generated name be <code class="classname">people</code>.</p><p>This decision was made after some debate, with the
        &#8220;<span class="quote">Principle of Least Surprise</span>&#8221; winning out in the
        end.</p></div><p>The strategy for generating a name after adding a
      <code class="interfacename">Set</code> or a <code class="interfacename">List</code>
      is to peek into the collection, take the short class name of the first object
      in the collection, and use that with <code class="literal">List</code> appended to the
      name. The same applies to arrays although with arrays it is not necessary to 
      peek into the array contents. A few examples will make the semantics of name
      generation for collections clearer:</p><div class="itemizedlist"><ul type="disc"><li><p>An <code class="classname">x.y.User[]</code> array with zero or more
          <code class="classname">x.y.User</code> elements added will have the name
          <code class="literal">userList</code> generated.</p></li><li><p>An <code class="classname">x.y.Foo[]</code> array with zero or more
          <code class="classname">x.y.User</code> elements added will have the name
          <code class="literal">fooList</code> generated.</p></li><li><p>A <code class="classname">java.util.ArrayList</code> with one or more
          <code class="classname">x.y.User</code> elements added will have the name
          <code class="literal">userList</code> generated.</p></li><li><p>A <code class="classname">java.util.HashSet</code> with one or more
          <code class="classname">x.y.Foo</code> elements added will have the name
          <code class="literal">fooList</code> generated.</p></li><li><p>An <span class="bold"><strong>empty</strong></span>
          <code class="classname">java.util.ArrayList</code> will not be added at all
          (in effect, the <code class="methodname">addObject(..)</code> call will
          essentially be a no-op).</p></li></ul></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-coc-r2vnt"></a>16.10.3&nbsp;The View -
      <code class="interfacename">RequestToViewNameTranslator</code></h3></div></div></div><p>The <code class="interfacename">RequestToViewNameTranslator</code>
      interface determines a logical <code class="interfacename">View</code> name
      when no such logical view name is explicitly supplied. It has just one
      implementation, the
      <code class="classname">DefaultRequestToViewNameTranslator</code> class.</p><p>The <code class="classname">DefaultRequestToViewNameTranslator</code> maps
      request URLs to logical view names, as with this example:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> RegistrationController <span class="hl-keyword">implements</span> Controller {
                
    <span class="hl-keyword">public</span> ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
        <span class="hl-comment">// process the request...</span>
        ModelAndView mav = <span class="hl-keyword">new</span> ModelAndView();
        <span class="hl-comment">// add data as necessary to the model...</span>
        <span class="hl-keyword">return</span> mav;
        <span class="hl-comment">// notice that no View or logical view name has been set</span>
    }
}</pre><pre class="programlisting">&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">!DOCTYPE</span> <span class="hl-attribute">beans</span> <span class="hl-attribute">PUBLIC</span> <span class="hl-attribute">"-//SPRING//DTD</span> <span class="hl-attribute">BEAN</span> <span class="hl-attribute">2.0//EN"</span>
        <span class="hl-attribute">"http://www.springframework.org/dtd/spring-beans-2.0.dtd"&gt;</span>
<span class="hl-attribute">&lt;beans&gt;</span>

    <span class="hl-attribute">&lt;!--</span> <span class="hl-attribute">this</span> <span class="hl-attribute">bean</span> <span class="hl-attribute">with</span> <span class="hl-attribute">the</span> <span class="hl-attribute">well</span> <span class="hl-attribute">known</span> <span class="hl-attribute">name</span> <span class="hl-attribute">generates</span> <span class="hl-attribute">view</span> <span class="hl-attribute">names</span> <span class="hl-attribute">for</span> <span class="hl-attribute">us</span> <span class="hl-attribute">--&gt;</span>
    <span class="hl-attribute">&lt;bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"viewNameTranslator"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator"</span>/&gt;

    &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"x.y.RegistrationController"</span>&gt;
        &lt;<span class="hl-comment">!-- inject dependencies as necessary --</span>&gt;
    &lt;<span class="hl-tag">/bean</span>&gt;
    
    &lt;<span class="hl-comment">!-- maps request URLs to Controller names --</span>&gt;
    &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"</span>/&gt;

    &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"viewResolver"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.view.InternalResourceViewResolver"</span>&gt;
        &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"prefix"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"/WEB-INF/jsp/"</span>/&gt;
        &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"suffix"</span> <span class="hl-attribute">value</span>=<span class="hl-value">".jsp"</span>/&gt;
    &lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">/beans</span>&gt;
</pre><p>Notice how in the implementation of the
      <code class="literal">handleRequest(..)</code> method no
      <code class="interfacename">View</code> or logical view name is ever set on
      the <code class="classname">ModelAndView</code> that is returned. The
      <code class="classname">DefaultRequestToViewNameTranslator</code> is tasked with
      generating a <span class="emphasis"><em>logical view name</em></span> from the URL of the
      request. In the case of the above
      <code class="classname">RegistrationController</code>, which is used in
      conjunction with the
      <code class="classname">ControllerClassNameHandlerMapping</code>, a request URL
      of <code class="literal">http://localhost/registration.html</code> results in a
      logical view name of <code class="literal">registration</code> being generated by
      the <code class="classname">DefaultRequestToViewNameTranslator</code>. This
      logical view name is then resolved into the
      <code class="literal">/WEB-INF/jsp/registration.jsp</code> view by the
      <code class="classname">InternalResourceViewResolver</code> bean.</p><div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Tip"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Tip]" src="images/tip.gif"></td><th align="left">Tip</th></tr><tr><td align="left" valign="top"><p>You do not need to define a
        <code class="classname">DefaultRequestToViewNameTranslator</code> bean
        explicitly. If you like the default settings of the
        <code class="classname">DefaultRequestToViewNameTranslator</code>, you can
        rely on the Spring Web MVC <code class="classname">DispatcherServlet</code> to
        instantiate an instance of this class if one is not explicitly
        configured.</p></td></tr></table></div><p>Of course, if you need to change the default settings, then you do
      need to configure your own
      <code class="classname">DefaultRequestToViewNameTranslator</code> bean
      explicitly. Consult the comprehensive Javadoc for the
      <code class="classname">DefaultRequestToViewNameTranslator</code> class for
      details of the various properties that can be configured.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="mvc-etag"></a>16.11&nbsp;ETag support</h2></div></div></div><p>An <a class="ulink" href="http://en.wikipedia.org/wiki/HTTP_ETag" target="_top">ETag</a>
    (entity tag) is an HTTP response header returned by an HTTP/1.1 compliant
    web server used to determine change in content at a given URL. It can be
    considered to be the more sophisticated successor to the
    <code class="literal">Last-Modified</code> header. When a server returns a
    representation with an ETag header, the client can use this header in
    subsequent GETs, in an <code class="literal">If-None-Match</code> header. If the
    content has not changed, the server returns <code class="literal">304: Not
    Modified</code>.</p><p>Support for ETags is provided by the servlet filter
    <code class="classname">ShallowEtagHeaderFilter</code>. It is a plain Servlet
    Filter, and thus can be used in combination with any web framework. The
    <code class="classname">ShallowEtagHeaderFilter</code> filter creates so-called
    shallow ETags (as opposed to deep ETags, more about that later).The
    filter caches the content of the rendered JSP (or other content),
    generates an MD5 hash over that, and returns that as an ETag header in the
    response. The next time a client sends a request for the same resource, it
    uses that hash as the <code class="literal">If-None-Match</code> value. The filter
    detects this, renders the view again, and compares the two hashes. If they
    are equal, a <code class="literal">304</code> is returned. This filter will not save
    processing power, as the view is still rendered. The only thing it saves
    is bandwidth, as the rendered response is not sent back over the
    wire.</p><p>You configure the <code class="classname">ShallowEtagHeaderFilter</code> in
    <code class="filename">web.xml</code>:</p><pre class="programlisting">&lt;<span class="hl-tag">filter</span>&gt;
  &lt;<span class="hl-tag">filter-name</span>&gt;etagFilter&lt;<span class="hl-tag">/filter-name</span>&gt;
    &lt;<span class="hl-tag">filter-class</span>&gt;org.springframework.web.filter.ShallowEtagHeaderFilter&lt;<span class="hl-tag">/filter-class</span>&gt;
&lt;<span class="hl-tag">/filter</span>&gt;

&lt;<span class="hl-tag">filter-mapping</span>&gt;
  &lt;<span class="hl-tag">filter-name</span>&gt;etagFilter&lt;<span class="hl-tag">/filter-name</span>&gt;
  &lt;<span class="hl-tag">servlet-name</span>&gt;petclinic&lt;<span class="hl-tag">/servlet-name</span>&gt;
&lt;<span class="hl-tag">/filter-mapping</span>&gt;</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="mvc-config"></a>16.12&nbsp;Configuring Spring MVC</h2></div></div></div><p>
  		Spring 3 introduces a <code class="literal">mvc</code> XML configuration namespace that simplifies the setup of Spring MVC inside your web application.
  		Instead of registering low-level beans such as AnnotationMethodHandlerAdapter, you can simply use the namespace and its higher-level constructs.
  		This is generally preferred unless you require finer-grained control of the configuration at the bean level.
  	</p><p>
  		The mvc namespace consists of three tags: mvc:annotation-driven, mvc:interceptors, and mvc:view-controller.
  		Each of these tags is documented below and in the <a class="ulink" href="http://static.springsource.org/schema/mvc/spring-mvc-3.0.xsd" target="_top">XML schema</a>.
  	</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-annotation-driven"></a>16.12.1&nbsp;mvc:annotation-driven</h3></div></div></div><p>
			This tag registers the RequestMappingHandlerMapping and RequestMappingHandlerAdapter beans that are required for Spring MVC to dispatch requests to @Controllers.
			The tag configures those two beans with sensible defaults based on what is present in your classpath.
			The defaults are:
    		</p><div class="orderedlist"><ol type="1"><li><p>
			    		Support for Spring 3's Type <a class="link" href="validation.html#core-convert" title="6.5&nbsp;Spring 3 Type Conversion">ConversionService</a> in addition to JavaBeans PropertyEditors during Data Binding.
			    		A ConversionService instance produced by the <code class="classname">org.springframework.format.support.FormattingConversionServiceFactoryBean</code> is used by default.
			    		This can be overridden by setting the <code class="literal">conversion-service</code> attribute. 
    				</p></li><li><p>
    					Support for <a class="link" href="validation.html#format" title="6.6&nbsp;Spring 3 Field Formatting">formatting</a> Number fields using the @NumberFormat annotation
    				</p></li><li><p>
					    Support for <a class="link" href="validation.html#format" title="6.6&nbsp;Spring 3 Field Formatting">formatting</a> Date, Calendar, Long, and Joda Time fields using the @DateTimeFormat annotation, if Joda Time 1.3 or higher is present on the classpath.
    				</p></li><li><p>
    					Support for <a class="link" href="validation.html#validation-mvc-jsr303" title="6.7.4.3&nbsp;Configuring a JSR-303 Validator for use by Spring MVC">validating</a> @Controller inputs with @Valid, if a JSR-303 Provider is present on the classpath.
    					The validation system can be explicitly configured by setting the <code class="literal">validator</code> attribute.
    				</p></li><li><p>
    					HttpMessageConverter support for @RequestBody method parameters and @ResponseBody method return values.
    				</p><p>
    					This is the complete list of HttpMessageConverters set up by mvc:annotation-driven:
				        </p><div class="itemizedlist"><ul type="disc"><li><p><code class="classname">ByteArrayHttpMessageConverter</code>
				            converts byte arrays.</p></li><li><p><code class="classname">StringHttpMessageConverter</code> converts
				            strings.</p></li><li><p><code class="classname">ResourceHttpMessageConverter</code> converts
				            to/from <code class="classname">org.springframework.core.io.Resource</code> 
				            for all media types.</p></li><li><p><code class="classname">SourceHttpMessageConverter</code> converts
				            to/from a <code class="classname">javax.xml.transform.Source</code>.</p></li><li><p><code class="classname">FormHttpMessageConverter</code> converts
				            form data to/from a <code class="classname">MultiValueMap&lt;String, String&gt;</code>.</p></li><li><p><code class="classname">Jaxb2RootElementHttpMessageConverter</code>
				            converts Java objects to/from XML -- added if JAXB2 is present 
				            on the classpath.
				            </p></li><li><p><code class="classname">MappingJacksonHttpMessageConverter</code>
				            converts to/from JSON -- added if Jackson is present on the classpath.
				            </p></li><li><p><code class="classname">AtomFeedHttpMessageConverter</code>
				            converts Atom feeds -- added if Rome is present on the classpath.
				            </p></li><li><p><code class="classname">RssChannelHttpMessageConverter</code>
				            converts RSS feeds -- added if Rome is present on the classpath.
				            </p></li></ul></div><p>
    				</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>
							You can provide your own HttpMessageConverters through the 
							mvc:message-converters sub-element of mvc:annotation-driven.
							Message converters you provide will take precedence over the 
							ones registered by default.
						</p></td></tr></table></div></li></ol></div><p>
    		A typical usage is shown below:
			</p><pre class="programlisting">
&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
    <span class="hl-attribute">xmlns:mvc</span>=<span class="hl-value">"http://www.springframework.org/schema/mvc"</span>
    <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
    <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"</span>&gt;

    &lt;<span class="hl-comment">!-- JSR-303 support will be detected on classpath and enabled automatically --</span>&gt;
    &lt;<span class="hl-tag">mvc:annotation-driven</span>/&gt;
    
&lt;<span class="hl-tag">/beans</span>&gt;
			</pre><p>   		
  		</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-interceptors"></a>16.12.2&nbsp;mvc:interceptors</h3></div></div></div><p>
  			This tag allows you to register custom HandlerInterceptors or WebRequestInterceptors that should be applied to all HandlerMapping beans.
  			You can also restrict the URL paths that specific interceptors apply to.
  		</p><p>
  			An example of registering an interceptor applied to all URL paths:
  		</p><pre class="programlisting">
&lt;<span class="hl-tag">mvc:interceptors</span>&gt;
    &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.web.servlet.i18n.LocaleChangeInterceptor"</span> /&gt;
&lt;<span class="hl-tag">/mvc:interceptors</span>&gt;
		</pre><p>
			An example of registering an interceptor limited to a specific URL path:
		</p><pre class="programlisting">
&lt;<span class="hl-tag">mvc:interceptors</span>&gt;
    &lt;<span class="hl-tag">mvc:interceptor</span>&gt;
        &lt;<span class="hl-tag">mapping</span> <span class="hl-attribute">path</span>=<span class="hl-value">"/secure/*"</span>/&gt;
        &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.example.SecurityInterceptor"</span> /&gt;
    &lt;<span class="hl-tag">/mvc:interceptor</span>&gt;
&lt;<span class="hl-tag">/mvc:interceptors</span>&gt;
		</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-view-controller"></a>16.12.3&nbsp;mvc:view-controller</h3></div></div></div><p>
  			This tag is a shortcut for defining a <code class="classname">ParameterizableViewController</code> that immediately forwards to a view when invoked.
  			Use it in static cases when there is no Java Controller logic to execute before the view generates the response.
  		</p><p>
  			An example of view-controller that forwards to a home page is shown below:
  		</p><pre class="programlisting">
&lt;<span class="hl-tag">mvc:view-controller</span> <span class="hl-attribute">path</span>=<span class="hl-value">"/"</span> <span class="hl-attribute">view-name</span>=<span class="hl-value">"home"</span>/&gt;
		</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-static-resources"></a>16.12.4&nbsp;mvc:resources</h3></div></div></div><p>
  			This tag allows static resource requests following a particular URL pattern to be served by a <code class="classname">ResourceHttpRequestHandler</code> from 
  			any of a list of <code class="classname">Resource</code> locations.  This provides a convenient way to serve static resources from locations other than the 
  			web application root, including locations on the classpath. The <code class="code">cache-period</code> property may be used to set far future expiration headers 
  			(1 year is the recommendation of optimization tools such as Page Speed and YSlow) so that they will be more efficiently utilized by the client.  The handler 
  			also properly evaluates the <code class="code">Last-Modified</code> header (if present) so that a <code class="code">304</code> status code will be returned as appropriate, avoiding 
  			unnecessary overhead for resources that are already cached by the client.  For example, to serve resource requests with a URL pattern of 
  			<code class="code">/resources/**</code> from a <code class="code">public-resources</code> directory within the web application root, the tag would be used as follows: 
  		</p><pre class="programlisting">
&lt;<span class="hl-tag">mvc:resources</span> <span class="hl-attribute">mapping</span>=<span class="hl-value">"/resources/**"</span> <span class="hl-attribute">location</span>=<span class="hl-value">"/public-resources/"</span>/&gt;
  		</pre><p>
  			To serve these resources with a 1-year future expiration to ensure maximum use of the browser cache and a reduction in HTTP requests made by the browser:
  		</p><pre class="programlisting">
&lt;<span class="hl-tag">mvc:resources</span> <span class="hl-attribute">mapping</span>=<span class="hl-value">"/resources/**"</span> <span class="hl-attribute">location</span>=<span class="hl-value">"/public-resources/"</span> <span class="hl-attribute">cache-period</span>=<span class="hl-value">"31556926"</span>/&gt;
  		</pre><p>
  			The <code class="code">mapping</code> attribute must be an Ant pattern that can be used by <code class="classname">SimpleUrlHandlerMapping</code>, and the <code class="code">location</code> 
  			attribute must specify one or more valid resource directory locations.  Multiple resource locations may be specified using a comma-separated list of values. 
  			The locations specified will be checked in the specified order for the presence of the resource for any given request.  For example, to enable the serving 
  			of resources from both the web application root and from a known path of <code class="code">/META-INF/public-web-resources/</code> in any jar on the classpath, the tag 
  			would be specified as: 
  		</p><pre class="programlisting">
&lt;<span class="hl-tag">mvc:resources</span> <span class="hl-attribute">mapping</span>=<span class="hl-value">"/resources/**"</span> <span class="hl-attribute">location</span>=<span class="hl-value">"/, classpath:/META-INF/public-web-resources/"</span>/&gt;
  		</pre><p>
  			When serving resources that may change when a new version of the application is deployed, it is recommended that you incorporate a version string into the 
  			mapping pattern used to request the resources, so that you may force clients to request the newly deployed version of your application's resources.  Such a 
  			version string can be parameterized and accessed using SpEL so that it may be easily managed in a single place when deploying new versions.
  		</p><p>  
  			As an example, let's consider an application that uses a performance-optimized custom build (as recommended) of the Dojo JavaScript library in production, and that the build is generally 
  			deployed within the web application at a path of <code class="code">/public-resources/dojo/dojo.js</code>.  Since different parts of Dojo may be incorporated into the 
  			custom build for each new version of the application, the client web browsers need to be forced to re-download that custom-built <code class="code">dojo.js</code> resource 
  			any time a new version of the application is deployed.  A simple way to achieve this would be to manage the version of the application in a properties file, 
  			such as:          
  		</p><pre class="programlisting">
application.version=1.0.0
  		</pre><p>
  			and then to make the properties file's values accessible to SpEL as a bean using the <code class="code">util:properties</code> tag:
  		</p><pre class="programlisting">
&lt;<span class="hl-tag">util:properties</span> <span class="hl-attribute">id</span>=<span class="hl-value">"applicationProps"</span> <span class="hl-attribute">location</span>=<span class="hl-value">"/WEB-INF/spring/application.properties"</span>/&gt;
  		</pre><p>
  			With the application version now accessible via SpEL, we can incorporate this into the use of the <code class="code">resources</code> tag:
  		</p><pre class="programlisting">
&lt;<span class="hl-tag">mvc:resources</span> <span class="hl-attribute">mapping</span>=<span class="hl-value">"/resources-#{applicationProps['application.version']}/**"</span> <span class="hl-attribute">location</span>=<span class="hl-value">"/public-resources/"</span>/&gt;
  		</pre><p>
  			and finally, to request the resource with the proper URL, we can take advantage of the Spring JSP tags:
  		</p><pre class="programlisting">
&lt;<span class="hl-tag">spring:eval</span> <span class="hl-attribute">expression</span>=<span class="hl-value">"@applicationProps['application.version']"</span> <span class="hl-attribute">var</span>=<span class="hl-value">"applicationVersion"</span>/&gt;

&lt;<span class="hl-tag">spring:url</span> <span class="hl-attribute">value</span>=<span class="hl-value">"/resources-{applicationVersion}"</span> <span class="hl-attribute">var</span>=<span class="hl-value">"resourceUrl"</span>&gt;
	&lt;<span class="hl-tag">spring:param</span> <span class="hl-attribute">name</span>=<span class="hl-value">"applicationVersion"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"${applicationVersion}"</span>/&gt;
&lt;<span class="hl-tag">/spring:url</span>&gt;

&lt;<span class="hl-tag">script</span> <span class="hl-attribute">src</span>=<span class="hl-value">"${resourceUrl}/dojo/dojo.js"</span> <span class="hl-attribute">type</span>=<span class="hl-value">"text/javascript"</span>&gt; &lt;<span class="hl-tag">/script</span>&gt;
  		</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="mvc-default-servlet-handler"></a>16.12.5&nbsp;mvc:default-servlet-handler</h3></div></div></div><p>
  			This tag allows for mapping the <code class="code">DispatcherServlet</code> to "/" (thus overriding the mapping of the container's default Servlet), 
  			while still allowing static resource requests to be handled by the container's default Servlet.  It configures a 
  			<code class="code">DefaultServletHttpRequestHandler</code> with a URL mapping of "/**" and the lowest priority relative to other URL mappings.  
  		</p><p>
  			This handler will forward all requests to the default Servlet. Therefore it is important that it remains last in the order of all
  			other URL <code class="code">HandlerMappings</code>. That will be the case if you use <code class="code">&lt;mvc:annotation-driven&gt;</code> or alternatively if you 
  			are setting up your own customized <code class="code">HandlerMapping</code> instance be sure to set its <code class="code">order</code> property to a value lower than 
  			that of the <code class="code">DefaultServletHttpRequestHandler</code>, which is <code class="code">Integer.MAX_VALUE</code>.
  		</p><p>
  			To enable the feature using the default setup, simply include the tag in the form:
  		</p><pre class="programlisting">
&lt;<span class="hl-tag">mvc:default-servlet-handler</span>/&gt;
  		</pre><p>
  			The caveat to overriding the "/" Servlet mapping is that the <code class="code">RequestDispatcher</code> for the default Servlet must be 
  			retrieved by name rather than by path.  The <code class="code">DefaultServletHttpRequestHandler</code> will attempt to auto-detect the default 
  			Servlet for the container at startup time, using a list of known names for most of the major Servlet containers (including Tomcat, 
  			Jetty, Glassfish, JBoss, Resin, WebLogic, and WebSphere).  If the default Servlet has been custom configured 
  			with a different name, or if a different Servlet container is being used where the default Servlet name is unknown, then the 
  			default Servlet's name must be explicitly provided as in the following example:
  		</p><pre class="programlisting">
&lt;<span class="hl-tag">mvc:default-servlet-handler</span> <span class="hl-attribute">default-servlet-name</span>=<span class="hl-value">"myCustomDefaultServlet"</span>/&gt;
  		</pre></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="mvc-resources"></a>16.13&nbsp;More Spring Web MVC Resources</h2></div></div></div><p>See the following links and pointers for more resources about Spring
    Web MVC:</p><div class="itemizedlist"><ul type="disc"><li><p>
			There are many excellent articles and tutorials that show how to build web applications with Spring MVC. 
			Read them at the <a class="ulink" href="http://www.springsource.org/documentation" target="_top">Spring Documentation</a> page.
		</p></li><li><p>&#8220;<span class="quote">Expert Spring Web MVC and Web Flow</span>&#8221; by Seth Ladd
        and others (published by Apress) is an excellent hard copy source of
        Spring Web MVC goodness.</p></li></ul></div></div></div><!--Begin LoopFuse code--><script src="http://loopfuse.net/webrecorder/js/listen.js" type="text/javascript"></script><script type="text/javascript">
			_lf_cid = "LF_48be82fa";
			_lf_remora();
		</script><!--End LoopFuse code--><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="spring-web.html">Prev</a>&nbsp;</td><td width="20%" align="center"><a accesskey="u" href="spring-web.html">Up</a></td><td width="40%" align="right">&nbsp;<a accesskey="n" href="view.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Part&nbsp;V.&nbsp;The Web&nbsp;</td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top">&nbsp;17.&nbsp;View technologies</td></tr></table></div></body></html>